Files
web-at-transit-mock/flow_ui/build_click_flow.py
T

874 lines
39 KiB
Python

#!/usr/bin/env python3
"""Horizontal click-flow diagram with row-aware centering and orthogonal arrows."""
import asyncio
import random
from pathlib import Path
from playwright.async_api import async_playwright
from PIL import Image, ImageDraw, ImageFont
from math import atan2, cos, sin
Image.MAX_IMAGE_PIXELS = None
ROOT = Path(__file__).resolve().parent.parent
UI_DIR = ROOT / "flow_ui" / "ui"
SHOTS_DIR = ROOT / "flow_ui" / "screenshots"
OUT_PNG = ROOT / "flow_ui" / "frontend-web-transit-flow.png"
VIEWPORT = {"width": 1600, "height": 1000}
OUTPUT_SCALE = 2
# id, page, selector_or_None, col, row, marker_label, panel_title, span_rows, align_mode
# row: integer row index (0=top). span_rows: if >1, node is centered across N rows.
# align_mode: "top" or "center-row" (centered vertically within its row band when span_rows == 1)
NODES = [
# Row 0 (top) — stop discovery flow
("N1", "index.html", None,
0, 0, "", "index.html", 1, "top"),
("N2a", "index.html", '.mu-nav a[href="./busStop.html"]',
1, 0, "คลิก 'ป้ายหยุดรถ'", "index.html · ป้ายหยุดรถ", 1, "top"),
("N3a", "busStop.html", ".mu-stop-grid li:nth-of-type(1) a.mu-row-link",
2, 0, "คลิกจุดจอด 'บขส.อ่างทอง'", "busStop.html", 1, "center-row"),
("N4a", "stopDetail.html", None,
4, 0, "ถึงรายละเอียดป้าย ?stop=at_main_terminal", "stopDetail.html", 1, "center-row"),
("N4b", "stopDetailExpanded.html", ".mu-stop-expander[open] .mu-route-chip",
5, 0, "ขยายข้อมูลเวลารถในป้าย", "stopDetail.html (expanded)", 1, "center-row"),
# Row 1 (bottom) — route detail flow
("N2b", "index.html", ".mu-zone:nth-of-type(3) .mu-card:nth-of-type(1)",
1, 1, "คลิกหมายเลขสาย 101", "index.html · สาย 101", 1, "top"),
("N3b", "busDetail.html", ".mu-stop-expander:nth-of-type(1) summary",
2, 1, "ขยายจุดจอด 'บขส.อ่างทอง'", "busDetail.html", 1, "center-row"),
("N4c", "busDetailExpanded.html", ".mu-stop-expander[open] .mu-inline-actions .mu-btn.ghost",
3, 1, "คลิก 'ไปหน้ารายละเอียดจุดจอด'", "busDetail.html (expanded)", 1, "center-row"),
]
EDGES = [
("N1", "N2a"), ("N1", "N2b"),
("N2a", "N3a"), ("N2b", "N3b"),
("N3a", "N4a"), ("N3b", "N4c"),
("N4c", "N4a"), ("N4a", "N4b"),
]
PAGES = sorted({n[1] for n in NODES})
STOP_DETAIL_ACTIONS = [
("A1", "stopDetail.html", "N4", "ดูตารางเวลาสายรถ", "busDetail.html", "N3", "?stop=at_main_terminal"),
("A2", "stopDetail.html", "N4", "เปิดรายละเอียดสาย 101", "busDetail.html", "N3", "?route=101&origin=at_main_terminal"),
("A3", "stopDetail.html", "N4", "กลับไปรายการป้าย", "busStop.html", "N2", "กลับหน้า list"),
("A4", "stopDetail.html", "N4", "กลับหน้าแรก (breadcrumb)", "index.html", "N1", "ผ่าน breadcrumb"),
("A5", "stopDetail.html", "N4", "ขยายเวลารถของสาย", "stopDetailExpanded", "N4e", "state transition"),
]
async def capture_all():
SHOTS_DIR.mkdir(parents=True, exist_ok=True)
boxes, sizes = {}, {}
state_page_map = {
"stopDetailExpanded.html": "stopDetail.html",
"busDetailExpanded.html": "busDetail.html",
}
async with async_playwright() as p:
browser = await p.chromium.launch()
ctx = await browser.new_context(viewport=VIEWPORT, device_scale_factor=1)
page = await ctx.new_page()
for name in PAGES:
# Expanded screenshots are captured from their base page with UI state toggled before snapshot.
source_name = state_page_map.get(name, name)
url = (UI_DIR / source_name).resolve().as_uri()
await page.goto(url, wait_until="networkidle")
await page.wait_for_timeout(400)
if name in state_page_map:
await page.evaluate(
"""
() => {
const first = document.querySelector('.mu-stop-expander');
if (first) first.open = true;
}
"""
)
await page.wait_for_timeout(120)
doc = await page.evaluate(
"({w: document.documentElement.scrollWidth, h: document.documentElement.scrollHeight})")
sizes[name] = (doc["w"], doc["h"])
await page.screenshot(path=str(SHOTS_DIR / name.replace(".html", ".png")), full_page=True)
for nid, p_name, sel, *_ in NODES:
if p_name != name or not sel:
continue
el = await page.query_selector(sel)
if not el:
print(f"WARN missing {sel} on {name}")
continue
boxes[nid] = await el.bounding_box()
print(f"captured {name} {sizes[name]}")
await browser.close()
return boxes, sizes
def get_font(size):
for path in [
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
"/System/Library/Fonts/Supplemental/Tahoma.ttf",
]:
try:
return ImageFont.truetype(path, size)
except Exception:
pass
return ImageFont.load_default()
def hex_to_rgb(value):
value = value.lstrip("#")
return tuple(int(value[i:i+2], 16) for i in (0, 2, 4))
def draw_cursor_icon(base_img, tip_x, tip_y, color_hex, scale=1.0):
# Render only the split two-prong motif (no main arrow-head triangle).
ss = 6
icon_w = int(30 * scale)
icon_h = int(30 * scale)
local = Image.new("RGBA", (icon_w * ss, icon_h * ss), (0, 0, 0, 0))
d = ImageDraw.Draw(local)
core = (int(9 * scale * ss), int(9 * scale * ss))
# Two-prong symbol balanced to avoid obscuring the center core.
prong_right = [
core,
(int(32 * scale * ss), int(18 * scale * ss)),
(int(19 * scale * ss), int(19 * scale * ss)),
]
prong_down = [
core,
(int(18 * scale * ss), int(32 * scale * ss)),
(int(19 * scale * ss), int(19 * scale * ss)),
]
connector = [
core,
(int(19 * scale * ss), int(19 * scale * ss)),
(int(16 * scale * ss), int(22 * scale * ss)),
(int(22 * scale * ss), int(16 * scale * ss)),
]
r, g, b = hex_to_rgb(color_hex)
d.polygon(prong_right, fill=(r, g, b, 248))
d.polygon(prong_down, fill=(r, g, b, 248))
d.polygon(connector, fill=(r, g, b, 248))
d.ellipse(
[
core[0] - int(1.6 * ss),
core[1] - int(1.6 * ss),
core[0] + int(1.6 * ss),
core[1] + int(1.6 * ss),
],
fill=(r, g, b, 255),
)
local = local.resize((icon_w, icon_h), Image.Resampling.LANCZOS)
px = int(tip_x - 8 * scale)
py = int(tip_y - 8 * scale)
base_img.paste(local, (px, py), local)
def compose(boxes, sizes):
s = OUTPUT_SCALE
cell_w = int(900 * s)
margin_h, margin_v = int(40 * s), int(30 * s)
# Keep enough horizontal/vertical whitespace so connectors stay visible.
gutter_h = int(440 * s)
row_gap = int(240 * s)
label_block_h = int(48 * s)
px_per_col = cell_w + gutter_h
grid = {}
for nid, page, sel, col, row, marker_lbl, title, span_rows, align_mode in NODES:
grid[nid] = {
"col": col, "row": row, "span_rows": span_rows,
"marker_label": marker_lbl, "title": title,
"align_mode": align_mode,
"page": page, "selector": sel
}
# Precompute scaled sizes for each node and dynamic row heights.
scaled_sizes = {}
for nid, page, *_ in NODES:
page_w, page_h = sizes.get(page, (cell_w, 800))
scale = cell_w / page_w if page_w else 1
scaled_w = int(page_w * scale)
scaled_h = int(page_h * scale)
scaled_sizes[nid] = (scaled_w, scaled_h)
unique_rows = sorted(set(n[4] for n in NODES))
row_heights = {}
for row in unique_rows:
row_nodes = [n[0] for n in NODES if n[4] == row]
row_heights[row] = max((scaled_sizes[nid][1] for nid in row_nodes), default=800)
row_tops = {}
cursor_y = margin_v
for row in unique_rows:
row_tops[row] = cursor_y
cursor_y += row_heights[row] + label_block_h + row_gap
# Compute bounds
cols = [n[3] for n in NODES]
rows = [n[4] for n in NODES]
max_col = max(cols) if cols else 0
max_row = max(rows) if rows else 0
canvas_w = (max_col + 1) * px_per_col + 2 * margin_h
canvas_h = cursor_y + margin_v
img = Image.new("RGB", (int(canvas_w), int(canvas_h)), "white")
draw = ImageDraw.Draw(img)
font_label = get_font(int(12 * s))
font_title = get_font(int(13 * s))
font_arrow = get_font(int(12 * s))
font_marker = get_font(int(11 * s))
# Per-node action color: deterministic random so output is stable across runs.
color_rng = random.Random(20260512)
color_palette = [
"#2563eb", "#7c3aed", "#db2777", "#ea580c",
"#0f766e", "#0891b2", "#4338ca", "#be123c",
]
action_colors = {nid: color_rng.choice(color_palette) for nid, *_ in NODES}
# Draw node panels: each is a screenshot at target grid cell with rounded corners
node_boxes = {}
click_points = {}
for nid, page, sel, col, row, marker_lbl, title, span_rows, align_mode in NODES:
# Load screenshot
png_path = SHOTS_DIR / page.replace(".html", ".png")
if not png_path.exists():
print(f"WARN no screenshot {png_path}")
continue
ss = Image.open(png_path)
page_w, page_h = ss.size
# Compute panel position
px = margin_h + col * px_per_col
py = row_tops[row] + label_block_h
# Scale screenshot
scale = cell_w / page_w
scaled_w = int(page_w * scale)
scaled_h = int(page_h * scale)
# Vertical centering within row band(s) for all nodes.
span_rows_list = [row + i for i in range(span_rows)]
band_h = sum(row_heights.get(r, row_heights[row]) for r in span_rows_list) + row_gap * (span_rows - 1)
if scaled_h < band_h:
py += (band_h - scaled_h) // 2
# Horizontal centering within column cell
if scaled_w < px_per_col:
px += (px_per_col - scaled_w) // 2
ss_scaled = ss.resize((scaled_w, scaled_h), Image.Resampling.LANCZOS)
# Paste onto main canvas
img.paste(ss_scaled, (int(px), int(py)))
# Record bounds for arrow drawing
node_boxes[nid] = (px, py, px + scaled_w, py + scaled_h)
# Record click marker position from selector bounding box on original page.
if nid in boxes and boxes[nid]:
b = boxes[nid]
cx = px + (b["x"] + b["width"] / 2) * scale
cy = py + (b["y"] + b["height"] / 2) * scale
click_points[nid] = (cx, cy)
# Add colored bar with filename/title and action description above screenshot.
action_color = action_colors.get(nid, "#1f4f7a")
bar_h = int(42 * s)
bar_y1 = py - label_block_h
bar_y2 = bar_y1 + bar_h
# Draw full-width colored bar
draw.rectangle([px, bar_y1, px + scaled_w, bar_y2], fill=action_color)
# Draw title and marker label inside bar
title_y = bar_y1 + int(12 * s)
draw.text((px + int(8 * s), title_y), title, fill="#ffffff", font=font_title, anchor="lm")
desc_y = bar_y1 + int(28 * s)
draw.text((px + int(8 * s), desc_y), marker_lbl, fill="#ffffff", font=font_label, anchor="lm")
def draw_edge_label(text, x, y, label_color="#1f4f7a"):
pad_x = int(12 * s)
pad_y = int(6 * s)
font_bold = get_font(int(14 * s))
text_w = draw.textlength(text, font=font_bold)
text_h = int(16 * s)
x1 = x - text_w / 2 - pad_x
y1 = y - text_h / 2 - pad_y
x2 = x + text_w / 2 + pad_x
y2 = y + text_h / 2 + pad_y
draw.rounded_rectangle([x1, y1, x2, y2], radius=int(8 * s), fill=label_color, outline="#ffffff", width=int(2 * s))
draw.text((x, y), text, fill="#ffffff", font=font_bold, anchor="mm")
def draw_soft_gradient_circle(base_img, cx, cy, rgb):
# Render gradient on a local RGBA surface, then composite to keep soft edges.
circle_scale = 1.3 * 1.2 * s
outer = int(round(20 * circle_scale))
inner = int(round(9 * circle_scale))
pad = int(4 * s)
size = outer * 2 + pad * 2
local = Image.new("RGBA", (size, size), (0, 0, 0, 0))
ld = ImageDraw.Draw(local)
center = outer + pad
r, g, b = rgb
# Outer soft halo.
for rr in range(outer, inner, -1):
t = (rr - inner) / max(1, (outer - inner))
alpha = int(12 + (1 - t) * 56)
ld.ellipse(
[center - rr, center - rr, center + rr, center + rr],
fill=(r, g, b, alpha),
)
# Inner light core for the "soft gradient" look.
for rr in range(inner, 2, -1):
t = rr / max(1, inner)
alpha = int(110 + (1 - t) * 80)
ld.ellipse(
[center - rr, center - rr, center + rr, center + rr],
fill=(255, 255, 255, alpha),
)
# Crisp center dot to preserve click focal point.
dot = max(2, int(2 * s))
ld.ellipse([center - dot, center - dot, center + dot, center + dot], fill=(r, g, b, 230))
base_img.paste(local, (cx - center, cy - center), local)
def draw_click_marker(nid, x, y):
# Normal cursor orientation with tip at click center.
cx = int(x)
cy = int(y)
action_color = action_colors.get(nid, "#334155")
r, g, b = hex_to_rgb(action_color)
# Soft gradient circle that shares the same hue as action label text.
draw_soft_gradient_circle(img, cx, cy, (r, g, b))
# Upright cursor with anti-aliased edges; tip lands exactly on click center.
draw_cursor_icon(img, cx, cy, action_color, scale=1.38 * s)
# Arrow routing: orthogonal with elbow
src_gap = int(15 * s)
dst_gap = int(10 * s)
def route_arrow(p1, p2, src_y_offset=0, dst_y_offset=0):
"""Return [(x_start, y0), (x_elbow, y0), (x_elbow, y1), (x_end, y1)]."""
x0, y0, x1_r, y1_r = p1
x2, y2, x3_r, y3_r = p2
src_y = (y0 + y1_r) / 2 + src_y_offset
dst_y = (y2 + y3_r) / 2 + dst_y_offset
mid_x = x1_r + (x2 - x1_r) * 0.25
return [(x1_r + src_gap, src_y), (mid_x, src_y), (mid_x, dst_y), (x2 - dst_gap, dst_y)]
arrow_width = int(5 * s)
# Count outgoing and incoming edges per node to compute per-edge y-offsets.
src_edge_counter = {}
dst_edge_counter = {}
for src, dst in EDGES:
src_edge_counter[src] = src_edge_counter.get(src, 0)
dst_edge_counter[dst] = dst_edge_counter.get(dst, 0)
src_seen = {k: 0 for k in src_edge_counter}
dst_seen = {k: 0 for k in dst_edge_counter}
src_labeled = set()
for src, dst in EDGES:
if src not in node_boxes or dst not in node_boxes:
continue
src_y_offset = src_seen[src] * int(4 * s)
dst_y_offset = 0
src_seen[src] += 1
dst_seen[dst] += 1
points = route_arrow(node_boxes[src], node_boxes[dst], src_y_offset=src_y_offset, dst_y_offset=dst_y_offset)
arrow_color = action_colors.get(src, "#0066cc")
# Compute arrowhead geometry first so line ends exactly at arrowhead base.
x_dst, y_dst = points[-1]
x_prev, y_prev = points[-2]
angle = atan2(y_dst - y_prev, x_dst - x_prev)
arr_len = arrow_width * 6
arr_w = arrow_width * 3
xa = x_dst - arr_len * cos(angle)
ya = y_dst - arr_len * sin(angle)
perp_angle = angle + 3.14159 / 2 # perpendicular (90 degrees) to arrow direction
xbl = xa + arr_w * cos(perp_angle)
ybl = ya + arr_w * sin(perp_angle)
xbr = xa - arr_w * cos(perp_angle)
ybr = ya - arr_w * sin(perp_angle)
# Draw line segments; last segment stops at arrowhead base (xa, ya).
for i in range(len(points) - 1):
x0, y0 = points[i]
x1, y1 = points[i + 1]
if i == len(points) - 2:
x1, y1 = xa, ya
draw.line([(x0, y0), (x1, y1)], fill=arrow_color, width=arrow_width)
# Draw arrowhead on top to create clean connection.
draw.polygon([(x_dst, y_dst), (xbl, ybl), (xbr, ybr)], fill=arrow_color)
# Add edge label above the final horizontal segment — only once per source.
lbl = grid.get(src, {}).get("marker_label", "")
if lbl and src not in src_labeled:
lx = (points[2][0] + points[3][0]) / 2
ly = points[2][1] - int(20 * s)
lbl_color = action_colors.get(src, "#1f4f7a")
draw_edge_label(lbl, lx, ly, lbl_color)
src_labeled.add(src)
# Draw click markers last so they stay above screenshots and arrows.
for nid, (cx, cy) in click_points.items():
draw_click_marker(nid, cx, cy)
# ── Stacked action-flow frames ──────────────────────────────────────────
# Layout constants
outer_pad = int(34 * s)
section_gap = int(30 * s)
header_h = int(70 * s)
footer_h = int(18 * s)
inner_pad = int(34 * s) # inside each frame
frame_tag_h = int(56 * s) # frame title-bar height
cell_pad = int(20 * s) # gutter between grid-line and cell box
cell_tag_h = int(34 * s) # per-cell label bar height
img_pad = int(12 * s) # space between cell-box edge and screenshot
arrow_gap = int(40 * s) # horizontal gutter between columns for arrows
# ONE global standard image width — every screenshot is scaled to exactly
# this many pixels wide; height follows the natural aspect ratio (no crop).
STANDARD_IMG_W = int(480 * s)
# Pre-read native screenshot dimensions from disk
def _shot_orig(name):
p = SHOTS_DIR / name.replace(".html", ".png")
if not p.exists():
return (1600, 900)
with Image.open(p) as im:
return im.size
_orig = {pg: _shot_orig(pg) for pg in [
"index.html", "busStop.html", "busDetail.html", "stopDetail.html",
"busDetailExpanded.html", "stopDetailExpanded.html",
]}
def _natural_h(page):
ow, oh = _orig.get(page, (1600, 900))
return int(oh * STANDARD_IMG_W / ow)
# ── Frame table definitions ─────────────────────────────────────────────
frame1_table = {
'cols': [
{'col': 0, 'rows': [
{'id': 'I', 'page': 'index.html', 'label': 'index.html', 'show_marker': False, 'emphasis_start': True},
]},
{'col': 1, 'rows': [
{'id': 'IA', 'page': 'index.html', 'label': 'index.html (คลิก "ป้ายหยุดรถ")', 'show_marker': True},
{'id': 'IB', 'page': 'index.html', 'label': 'index.html (คลิก "คลิกหมายเลขสาย 101")', 'show_marker': True},
]},
{'col': 2, 'rows': [
{'id': 'S', 'page': 'busStop.html', 'label': 'busStop.html', 'show_marker': False, 'emphasis_end': True},
{'id': 'B', 'page': 'busDetail.html', 'label': 'busDetail.html', 'show_marker': False, 'emphasis_end': True},
]},
],
'edges': [
{'src': 'I', 'dst': 'IA', 'label': 'คลิก "ป้ายหยุดรถ"', 'color': '#2563eb'},
{'src': 'I', 'dst': 'IB', 'label': 'คลิกหมายเลขสาย 101', 'color': '#2563eb'},
{'src': 'IA', 'dst': 'S', 'label': 'ไป busStop', 'color': '#2563eb'},
{'src': 'IB', 'dst': 'B', 'label': 'ไป busDetail', 'color': '#2563eb'},
],
}
frame2_table = {
'cols': [
{'col': 0, 'rows': [{'id': 'S', 'page': 'busStop.html', 'label': 'busStop.html', 'show_marker': False, 'emphasis_start': True}]},
{'col': 1, 'rows': [{'id': 'SC', 'page': 'busStop.html', 'label': 'busStop.html (คลิก "บขส.อ่างทอง")', 'show_marker': True, 'marker_box_id': 'N3a'}]},
{'col': 2, 'rows': [{'id': 'D', 'page': 'stopDetail.html', 'label': 'stopDetail.html', 'show_marker': False}]},
{'col': 3, 'rows': [{'id': 'BE', 'page': 'busDetailExpanded.html','label': 'busDetail (expanded)', 'show_marker': True}]},
{'col': 4, 'rows': [{'id': 'DE', 'page': 'stopDetailExpanded.html','label':'stopDetail (expanded)', 'show_marker': True}]},
{'col': 5, 'rows': [{'id': 'B', 'page': 'busDetail.html', 'label': 'busDetail.html', 'show_marker': False, 'emphasis_end': True}]},
],
'edges': [
{'src': 'S', 'dst': 'SC', 'label': 'คลิก "บขส.อ่างทอง"', 'color': '#7c3aed'},
{'src': 'SC', 'dst': 'D', 'label': 'ไป stopDetail', 'color': '#7c3aed'},
{'src': 'D', 'dst': 'BE', 'label': 'ไป busDetail(exp)', 'color': '#7c3aed'},
{'src': 'BE', 'dst': 'DE', 'label': 'ไป stopDetail(exp)', 'color': '#7c3aed'},
{'src': 'DE', 'dst': 'B', 'label': 'สิ้นสุด busDetail', 'color': '#7c3aed'},
],
}
frame3_table = {
'cols': [
{'col': 0, 'rows': [{'id': 'B', 'page': 'busDetail.html', 'label': 'busDetail.html', 'show_marker': False, 'emphasis_start': True}]},
{'col': 1, 'rows': [{'id': 'BE', 'page': 'busDetailExpanded.html', 'label': 'busDetail (expanded)', 'show_marker': True}]},
{'col': 2, 'rows': [{'id': 'DE', 'page': 'stopDetailExpanded.html','label': 'stopDetail (expanded)', 'show_marker': True}]},
{'col': 3, 'rows': [{'id': 'D', 'page': 'stopDetail.html', 'label': 'stopDetail.html', 'show_marker': False, 'emphasis_end': True}]},
],
'edges': [
{'src': 'B', 'dst': 'BE', 'label': 'ไป busDetail(exp)', 'color': '#0f766e'},
{'src': 'BE', 'dst': 'DE', 'label': 'ไป stopDetail(exp)', 'color': '#0f766e'},
{'src': 'DE', 'dst': 'D', 'label': 'สิ้นสุด stopDetail','color': '#0f766e'},
],
}
FRAMES = [
(frame1_table, "#2563eb",
"index.html action flow",
"start at index.html → busStop.html / busDetail.html"),
(frame2_table, "#7c3aed",
"busStop action flow",
"busStop → stopDetail → busDetail(exp) → stopDetail(exp) → busDetail"),
(frame3_table, "#0f766e",
"busDetail action flow",
"busDetail → busDetail(exp) → stopDetail(exp) → stopDetail"),
]
# Pages that are used as a flow start. Reuse the same "start signature"
# frame style whenever these pages appear in other flows.
START_SIGNATURE_PAGES = {
node['page']
for table, *_ in FRAMES
for col in table['cols']
for node in col['rows']
if node.get('emphasis_start')
}
START_SIGNATURE_PAGE_TINT = {
node['page']: tint
for table, tint, *_ in FRAMES
for col in table['cols']
for node in col['rows']
if node.get('emphasis_start')
}
# ── Dynamic layout computation ──────────────────────────────────────────
# cell content width: STANDARD_IMG_W + padding on both sides
cell_content_w = STANDARD_IMG_W + 2 * img_pad
# full column width (cell box + gutter)
col_slot_w = cell_content_w + 2 * cell_pad + arrow_gap
def _row_img_heights(table):
"""Per-row max natural image height at STANDARD_IMG_W."""
cols = table['cols']
max_rows = max(len(c['rows']) for c in cols)
heights = []
for ri in range(max_rows):
mh = 0
for c in cols:
if ri < len(c['rows']):
mh = max(mh, _natural_h(c['rows'][ri]['page']))
heights.append(mh)
return heights
def _frame_h(row_img_heights):
rows_total = sum(
cell_tag_h + 2 * img_pad + h + 2 * cell_pad
for h in row_img_heights
)
return frame_tag_h + 2 * inner_pad + rows_total
def _frame_content_w(table):
return len(table['cols']) * col_slot_w
all_row_heights = [_row_img_heights(t) for t, *_ in FRAMES]
all_frame_h = [_frame_h(rh) for rh in all_row_heights]
frame_w = max(_frame_content_w(t) for t, *_ in FRAMES) + 2 * inner_pad
frame_w = max(frame_w, int(2000 * s))
total_h = (outer_pad + header_h
+ sum(all_frame_h)
+ section_gap * (len(FRAMES) - 1)
+ footer_h + outer_pad)
final_img = Image.new("RGBA", (outer_pad * 2 + frame_w, total_h), "#f4f7ff")
final_draw = ImageDraw.Draw(final_img)
# ── Helper functions ────────────────────────────────────────────────────
def mix_rgb(c1, c2, t):
return (
int(c1[0] + (c2[0] - c1[0]) * t),
int(c1[1] + (c2[1] - c1[1]) * t),
int(c1[2] + (c2[2] - c1[2]) * t),
)
def tint_towards_white(hex_color, strength):
base = hex_to_rgb(hex_color)
return mix_rgb(base, (255, 255, 255), strength)
def draw_linear_gradient(rect, c1, c2, vertical=True):
x1, y1, x2, y2 = [int(v) for v in rect]
if vertical:
h = max(1, y2 - y1)
for i in range(h):
t = i / max(1, h - 1)
final_draw.line([(x1, y1 + i), (x2, y1 + i)], fill=mix_rgb(c1, c2, t))
else:
w = max(1, x2 - x1)
for i in range(w):
t = i / max(1, w - 1)
final_draw.line([(x1 + i, y1), (x1 + i, y2)], fill=mix_rgb(c1, c2, t))
def draw_soft_rounded_gradient(rect, radius, c1, c2, outline=None, outline_w=1, vertical=True):
x1, y1, x2, y2 = [int(v) for v in rect]
w = max(1, x2 - x1)
h = max(1, y2 - y1)
grad = Image.new("RGBA", (w, h), (0, 0, 0, 0))
gd = ImageDraw.Draw(grad)
if vertical:
for i in range(h):
t = i / max(1, h - 1)
gd.line([(0, i), (w, i)], fill=(*mix_rgb(c1, c2, t), 255))
else:
for i in range(w):
t = i / max(1, w - 1)
gd.line([(i, 0), (i, h)], fill=(*mix_rgb(c1, c2, t), 255))
mask = Image.new("L", (w, h), 0)
md = ImageDraw.Draw(mask)
md.rounded_rectangle([0, 0, w - 1, h - 1], radius=radius, fill=255)
final_img.paste(grad, (x1, y1), mask)
if outline:
final_draw.rounded_rectangle([x1, y1, x2, y2], radius=radius, outline=outline, width=outline_w)
bg_c1 = (246, 248, 255)
bg_c2 = (237, 245, 255)
draw_linear_gradient([0, 0, final_img.width, final_img.height], bg_c1, bg_c2, vertical=True)
def fit_shot_std(name):
"""Scale screenshot to exactly STANDARD_IMG_W; height is natural (no crop)."""
p = SHOTS_DIR / name.replace(".html", ".png")
if not p.exists():
return None
shot = Image.open(p).convert("RGB")
new_h = int(shot.height * STANDARD_IMG_W / shot.width)
return shot.resize((STANDARD_IMG_W, new_h), Image.Resampling.LANCZOS)
def place_cell(col_x1, row_y1, page_name, label, tint, row_img_h, node_def=None, shared_start_pages=None, shared_start_tints=None):
"""
Draw one table cell: label bar + screenshot at STANDARD_IMG_W.
Cell is vertically centered inside a row band driven by row_img_h.
Returns both frame and screenshot bounds for downstream routing.
"""
cx1 = col_x1 + cell_pad
cx2 = cx1 + cell_content_w
# Fit each frame to the actual image height so the border hugs the image.
shot = fit_shot_std(page_name)
content_h = shot.height if shot is not None else row_img_h
cell_h = cell_tag_h + 2 * img_pad + content_h + 2 * cell_pad
row_h = cell_tag_h + 2 * img_pad + row_img_h + 2 * cell_pad
cy1 = row_y1 + max(0, (row_h - cell_h) // 2)
cy2 = cy1 + cell_h
# Determine emphasis state for highlight
is_emphasis_start = node_def and node_def.get('emphasis_start')
is_emphasis_end = node_def and node_def.get('emphasis_end')
has_click_marker = bool(node_def and node_def.get('show_marker'))
is_clean_node = not has_click_marker
is_shared_start_page = bool(shared_start_pages and page_name in shared_start_pages)
is_start_signature = bool((is_emphasis_start or is_shared_start_page) and is_clean_node)
signature_tint = tint
if is_start_signature and shared_start_tints and page_name in shared_start_tints:
signature_tint = shared_start_tints[page_name]
tint_rgb = hex_to_rgb(tint)
signature_tint_rgb = hex_to_rgb(signature_tint)
cell_top = tint_towards_white(tint, 0.94)
cell_bottom = tint_towards_white(tint, 0.88)
# Start-signature redesign: stronger visual presence with an outer ring.
if is_start_signature:
ring_pad = int(10 * s)
ring_top = tint_towards_white(signature_tint, 0.84)
ring_bottom = tint_towards_white(signature_tint, 0.68)
draw_soft_rounded_gradient(
[cx1 - ring_pad, cy1 - ring_pad, cx2 + ring_pad, cy2 + ring_pad],
radius=int(18 * s),
c1=ring_top,
c2=ring_bottom,
outline=signature_tint,
outline_w=int(2 * s),
vertical=True,
)
cell_top = tint_towards_white(signature_tint, 0.90)
cell_bottom = tint_towards_white(signature_tint, 0.78)
# Cell box with enhanced border for emphasized nodes
border_width = int(8 * s) if is_start_signature else (int(6 * s) if is_emphasis_end else int(3 * s))
draw_soft_rounded_gradient(
[cx1, cy1, cx2, cy2],
radius=int(14 * s),
c1=cell_top,
c2=cell_bottom,
outline=signature_tint if is_start_signature else tint,
outline_w=border_width,
vertical=True,
)
if is_start_signature:
# Double-edge look for start frames to make them stand out from others.
inner_pad = int(8 * s)
final_draw.rounded_rectangle(
[cx1 + inner_pad, cy1 + inner_pad, cx2 - inner_pad, cy2 - inner_pad],
radius=int(10 * s), outline=signature_tint, width=int(2 * s)
)
# Label bar
bar_color_rgb = signature_tint_rgb if is_start_signature else tint_rgb
bar_top = mix_rgb(bar_color_rgb, (255, 255, 255), 0.12) if is_start_signature else mix_rgb(bar_color_rgb, (255, 255, 255), 0.22)
bar_bottom = mix_rgb(bar_color_rgb, (255, 255, 255), 0.02) if is_start_signature else mix_rgb(bar_color_rgb, (255, 255, 255), 0.08)
draw_soft_rounded_gradient(
[cx1, cy1, cx2, cy1 + cell_tag_h],
radius=int(12 * s),
c1=bar_top,
c2=bar_bottom,
outline=None,
vertical=True,
)
final_draw.rectangle([cx1, cy1 + cell_tag_h - int(6 * s), cx2, cy1 + cell_tag_h],
fill=bar_bottom)
final_draw.text((cx1 + int(10 * s), cy1 + int(18 * s)),
label, fill="#ffffff", font=get_font(int(11 * s)), anchor="lm")
# Screenshot — always STANDARD_IMG_W wide
ix = cx1 + img_pad
iy = cy1 + cell_tag_h + img_pad
if shot is not None:
final_img.paste(shot, (int(ix), int(iy)))
return {
"frame": (int(cx1), int(cy1), int(cx2), int(cy2)),
"image": (int(ix), int(iy), int(ix) + shot.width, int(iy) + shot.height),
}
else:
mx = (cx1 + cx2) // 2
my = (cy1 + cy2) // 2
final_draw.text((mx, my), page_name, fill="#64748b",
font=get_font(int(10 * s)), anchor="mm")
return {
"frame": (int(cx1), int(cy1), int(cx2), int(cy2)),
"image": (int(cx1), int(cy1), int(cx2), int(cy2)),
}
def draw_frame_box(rect, title, subtitle, tint):
x1, y1, x2, y2 = rect
frame_top = tint_towards_white(tint, 0.96)
frame_bottom = tint_towards_white(tint, 0.90)
draw_soft_rounded_gradient(
[x1, y1, x2, y2],
radius=int(18 * s),
c1=frame_top,
c2=frame_bottom,
outline=tint,
outline_w=int(3 * s),
vertical=True,
)
bar_h = int(48 * s)
tint_rgb = hex_to_rgb(tint)
bar_top = mix_rgb(tint_rgb, (255, 255, 255), 0.20)
bar_bottom = mix_rgb(tint_rgb, (255, 255, 255), 0.04)
draw_soft_rounded_gradient(
[x1, y1, x2, y1 + bar_h],
radius=int(16 * s),
c1=bar_top,
c2=bar_bottom,
outline=None,
vertical=True,
)
final_draw.rectangle([x1, y1 + bar_h - int(8 * s), x2, y1 + bar_h], fill=bar_bottom)
final_draw.text((x1 + int(12 * s), y1 + int(16 * s)),
title, fill="#ffffff", font=get_font(int(14 * s)), anchor="lm")
final_draw.text((x1 + int(12 * s), y1 + int(36 * s)),
subtitle, fill="#edf2ff", font=get_font(int(11 * s)), anchor="lm")
def draw_arrow_with_label(sx, sy, dx, dy, label, color):
mid_x = sx + (dx - sx) * 0.45
path = [(sx, sy), (mid_x, sy), (mid_x, dy), (dx, dy)]
for i in range(len(path) - 1):
final_draw.line([path[i], path[i + 1]], fill=color, width=int(4 * s))
angle = atan2(dy - path[-2][1], dx - path[-2][0])
aln, alw = int(16 * s), int(9 * s)
xa = dx - aln * cos(angle); ya = dy - aln * sin(angle)
perp = angle + 3.14159 / 2
final_draw.polygon([(dx, dy),
(xa + alw * cos(perp), ya + alw * sin(perp)),
(xa - alw * cos(perp), ya - alw * sin(perp))], fill=color)
lx = (path[1][0] + path[2][0]) / 2
ly = min(path[1][1], path[2][1]) - int(16 * s)
tw = final_draw.textlength(label, font=get_font(int(11 * s)))
final_draw.rounded_rectangle(
[lx - tw / 2 - int(10 * s), ly - int(17 * s),
lx + tw / 2 + int(10 * s), ly + int(6 * s)],
radius=int(8 * s), fill=color)
final_draw.text((lx, ly - int(4 * s)), label,
fill="#ffffff", font=get_font(int(11 * s)), anchor="mm")
def render_frame(frame_rect, table, tint, row_img_heights):
fx1, fy1, fx2, fy2 = frame_rect
# Content area starts below frame title bar
cx1 = fx1 + inner_pad
cy1 = fy1 + frame_tag_h + inner_pad
cols = table['cols']
max_rows = max(len(c['rows']) for c in cols)
# Build cumulative row y-positions
row_tops = []
cy = cy1
for rh in row_img_heights:
row_tops.append(cy)
cy += cell_tag_h + 2 * img_pad + rh + 2 * cell_pad
node_boxes = {}
for col_idx, col in enumerate(cols):
col_x1 = cx1 + col_idx * col_slot_w
for row_idx, node in enumerate(col['rows']):
rh = row_img_heights[row_idx]
bbox = place_cell(col_x1, row_tops[row_idx],
node['page'], node['label'], tint, rh, node_def=node,
shared_start_pages=START_SIGNATURE_PAGES,
shared_start_tints=START_SIGNATURE_PAGE_TINT)
node_boxes[node['id']] = bbox
if col_idx < len(cols) - 1:
sep_x = col_x1 + col_slot_w - arrow_gap // 2
final_draw.line([sep_x, int(cy1), sep_x, int(cy)],
fill="#d1d5db", width=int(2 * s))
# Draw horizontal row separator before each row > 0 in this column
if row_idx > 0:
sep_y = row_tops[row_idx]
final_draw.line([col_x1, sep_y, col_x1 + col_slot_w, sep_y],
fill="#d1d5db", width=int(2 * s))
# Click markers
for node_id, bounds in node_boxes.items():
node_def = next(
n for c in cols for n in c['rows'] if n['id'] == node_id)
if node_def.get('show_marker'):
bbox = bounds['image']
cmx = int((bbox[0] + bbox[2]) / 2)
cmy = int((bbox[1] + bbox[3]) / 2)
marker_box_id = node_def.get('marker_box_id')
if marker_box_id and marker_box_id in boxes:
mb = boxes[marker_box_id]
page_w = _orig.get(node_def['page'], (1600, 900))[0]
scale = (bbox[2] - bbox[0]) / page_w if page_w else 1
cmx = int(bbox[0] + (mb['x'] + mb['width'] / 2) * scale)
cmy = int(bbox[1] + (mb['y'] + mb['height'] / 2) * scale)
r, g, b = hex_to_rgb(tint)
draw_soft_gradient_circle(final_img, cmx, cmy, (r, g, b))
draw_cursor_icon(final_img, cmx, cmy, tint, scale=1.38 * s)
# Arrows
for edge in table['edges']:
src_bounds = node_boxes.get(edge['src'])
dst_bounds = node_boxes.get(edge['dst'])
if src_bounds is None or dst_bounds is None:
continue
src_frame = src_bounds['frame']
dst_frame = dst_bounds['frame']
dst_x = dst_frame[0] - int(6 * s)
draw_arrow_with_label(
src_frame[2], (src_frame[1] + src_frame[3]) / 2,
dst_x, (dst_frame[1] + dst_frame[3]) / 2,
edge['label'], edge['color'])
# ── Compose canvas ──────────────────────────────────────────────────────
final_draw.text((outer_pad, outer_pad + int(18 * s)),
"AT Transit Action Flow (Stacked Frames)",
fill="#1f2a44", font=get_font(int(18 * s)), anchor="lm")
cursor_y = outer_pad + header_h
for (table, tint, title, subtitle), rh_list, fh in zip(FRAMES, all_row_heights, all_frame_h):
frame_rect = (outer_pad, cursor_y, outer_pad + frame_w, cursor_y + fh)
draw_frame_box(frame_rect, title, subtitle, tint)
render_frame(frame_rect, table, tint, rh_list)
cursor_y += fh + section_gap
final_img.convert("RGB").save(OUT_PNG)
print(f"saved {OUT_PNG}")
if __name__ == "__main__":
print("Capturing screenshots...")
boxes, sizes = asyncio.run(capture_all())
print(f"Composing diagram with {len(NODES)} nodes...")
compose(boxes, sizes)