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

259 lines
9.6 KiB
Python

#!/usr/bin/env python3
"""Capture the live web app and compose a flow UI diagram.
Reads pages from http://localhost:13000 (override via FRONTEND_BASE env),
captures full-page screenshots, then composes a 2-row click-flow diagram:
Row A (top, stop discovery): / → /stops → /stops/details?code=<code>
Row B (bottom, route detail): / → /routes → /routes/<id>
Includes the cross-flow action from the stop timetable back to route detail.
The index node spans both rows.
Outputs:
- flow_ui/frontend-web-transit-flow-live.png
- flow_ui/frontend-web-transit-flow-live.jpg
"""
import asyncio
import os
from pathlib import Path
from math import atan2, cos, sin, pi
from PIL import Image, ImageDraw, ImageFont
from playwright.async_api import async_playwright
Image.MAX_IMAGE_PIXELS = None
ROOT = Path(__file__).resolve().parent
SHOTS_DIR = ROOT / "screenshots_live"
OUT_PNG = ROOT / "frontend-web-transit-flow-live.png"
OUT_JPG = ROOT / "frontend-web-transit-flow-live.jpg"
BASE = os.environ.get("FRONTEND_BASE", "http://localhost:13000")
STOP_CODE = os.environ.get("STOP_CODE", "at_main_terminal")
ROUTE_ID = os.environ.get("ROUTE_ID", "101")
VIEWPORT = {"width": 1440, "height": 900}
OUTPUT_SCALE = 2 # super-sample for crisp text
# id, url_path, file_stem, col, row, span_rows, header_title, edge_label_in
NODES = [
("HOME", "/", "home", 0, 0, 2, "หน้าแรก · /", ""),
("STOPS", "/stops", "stops", 1, 0, 1, "/stops · ค้นหาป้ายหยุดรถ", 'คลิก "ค้นหาป้ายหยุดรถ"'),
("STOP", f"/stops/details?code={STOP_CODE}", "stop", 2, 0, 1, f"/stops/details?code={STOP_CODE} · รายละเอียดป้าย", "คลิกการ์ดป้ายแรก"),
("ROUTES","/routes", "routes", 1, 1, 1, "/routes · รายการสายรถ", 'คลิก "รายละเอียดสายรถ"'),
("ROUTE", f"/routes/{ROUTE_ID}", "route", 2, 1, 1, f"/routes/{ROUTE_ID} · รายละเอียดสาย", "คลิกการ์ดสายรถ"),
]
EDGES = [
("HOME", "STOPS"),
("STOPS", "STOP"),
("HOME", "ROUTES"),
("ROUTES", "ROUTE"),
("STOP", "ROUTE"),
]
COLORS = {
"HOME": "#0f766e",
"STOPS": "#2563eb",
"STOP": "#7c3aed",
"ROUTES": "#ea580c",
"ROUTE": "#db2777",
}
async def capture_all():
SHOTS_DIR.mkdir(parents=True, exist_ok=True)
sizes = {}
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 nid, path, stem, *_ in NODES:
url = f"{BASE}{path}"
try:
await page.goto(url, wait_until="networkidle", timeout=20000)
except Exception as e:
print(f"WARN load {url}: {e}")
await page.goto(url, wait_until="domcontentloaded", timeout=20000)
await page.wait_for_timeout(600)
doc = await page.evaluate(
"({w: document.documentElement.scrollWidth, h: document.documentElement.scrollHeight})"
)
sizes[nid] = (doc["w"], doc["h"])
out = SHOTS_DIR / f"{stem}.png"
await page.screenshot(path=str(out), full_page=True)
print(f"captured {nid:6s} {url} {sizes[nid]}")
await browser.close()
return 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:
continue
return ImageFont.load_default()
def compose(sizes):
s = OUTPUT_SCALE
cell_w = int(720 * s)
gutter_h = int(320 * s)
row_gap = int(180 * s)
margin_h = int(60 * s)
margin_v = int(70 * s)
header_h = int(54 * s)
title_h = int(70 * s)
px_per_col = cell_w + gutter_h
# Scaled per-node size (cell_w wide, proportional height)
scaled = {}
for nid, *_ in NODES:
ow, oh = sizes.get(nid, (1440, 900))
sw = cell_w
sh = int(oh * (cell_w / ow))
scaled[nid] = (sw, sh)
rows = sorted({n[4] for n in NODES})
# Per-row band height = tallest non-spanning node in that row
row_band = {}
for r in rows:
candidates = [scaled[n[0]][1] for n in NODES if n[4] == r and n[5] == 1]
row_band[r] = max(candidates) if candidates else 800
row_tops = {}
y = margin_v + title_h
for r in rows:
row_tops[r] = y
y += header_h + row_band[r] + row_gap
canvas_h = y + margin_v
max_col = max(n[3] for n in NODES)
canvas_w = margin_h * 2 + (max_col + 1) * cell_w + max_col * gutter_h
img = Image.new("RGB", (canvas_w, canvas_h), "#f7f8fb")
draw = ImageDraw.Draw(img)
font_title = get_font(int(28 * s))
font_header = get_font(int(15 * s))
font_label = get_font(int(15 * s))
# Diagram title
draw.text((margin_h, int(margin_v * 0.45)),
"AT Transit · Web UI Flow (live)",
fill="#0f172a", font=font_title)
sub = f"Captured from {BASE} · stop={STOP_CODE} · route={ROUTE_ID}"
draw.text((margin_h, int(margin_v * 0.45) + int(36 * s)),
sub, fill="#475569", font=font_header)
boxes = {}
for nid, path, stem, col, row, span, header, edge_label in NODES:
png_path = SHOTS_DIR / f"{stem}.png"
if not png_path.exists():
print(f"WARN no screenshot {png_path}")
continue
sw, sh = scaled[nid]
px = margin_h + col * (cell_w + gutter_h)
if span > 1:
# Span across the listed rows: vertical center the panel across the bands
spanned = rows[:span] if rows[0] == row else rows[row:row+span]
band_top = row_tops[spanned[0]]
band_bot = row_tops[spanned[-1]] + header_h + row_band[spanned[-1]]
avail = band_bot - band_top - header_h
py = band_top + header_h + max(0, (avail - sh) // 2)
else:
py = row_tops[row] + header_h + max(0, (row_band[row] - sh) // 2)
# Header bar
color = COLORS.get(nid, "#1f4f7a")
draw.rectangle([px, py - header_h, px + sw, py], fill=color)
draw.text((px + int(14 * s), py - header_h + int(14 * s)),
header, fill="#ffffff", font=font_header)
draw.text((px + int(14 * s), py - header_h + int(34 * s)),
path, fill="#e2e8f0", font=font_label)
# Screenshot with subtle border
ss = Image.open(png_path).convert("RGB").resize((sw, sh), Image.Resampling.LANCZOS)
img.paste(ss, (px, py))
draw.rectangle([px, py, px + sw - 1, py + sh - 1], outline="#cbd5e1", width=max(1, int(1.5 * s)))
boxes[nid] = (px, py - header_h, px + sw, py + sh)
# Edges (orthogonal with arrowhead + pill label)
arrow_w = max(3, int(4 * s))
def pill(x, y, text, color):
f = get_font(int(15 * s))
tw = draw.textlength(text, font=f)
th = int(20 * s)
pad_x, pad_y = int(14 * s), int(7 * s)
x1, y1 = x - tw / 2 - pad_x, y - th / 2 - pad_y
x2, y2 = x + tw / 2 + pad_x, y + th / 2 + pad_y
draw.rounded_rectangle([x1, y1, x2, y2], radius=int(10 * s),
fill=color, outline="#ffffff", width=max(1, int(2 * s)))
draw.text((x, y), text, fill="#ffffff", font=f, anchor="mm")
src_offset = {n[0]: 0 for n in NODES}
label_for = {n[0]: n[7] for n in NODES}
for src, dst in EDGES:
if src not in boxes or dst not in boxes:
continue
sx1, sy1, sx2, sy2 = boxes[src]
dx1, dy1, dx2, dy2 = boxes[dst]
# vertical anchor: row center of node body (excluding header)
s_cy = (sy1 + header_h + sy2) / 2 + src_offset[src] * int(28 * s)
d_cy = (dy1 + header_h + dy2) / 2
src_offset[src] += 1
x_start = sx2
x_end = dx1
x_mid = x_start + (x_end - x_start) * 0.5
pts = [(x_start, s_cy), (x_mid, s_cy), (x_mid, d_cy), (x_end, d_cy)]
# arrowhead
ax, ay = pts[-1]
bx, by = pts[-2]
ang = atan2(ay - by, ax - bx)
head_len = arrow_w * 5
head_w = arrow_w * 3
hx = ax - head_len * cos(ang)
hy = ay - head_len * sin(ang)
perp = ang + pi / 2
lx, ly = hx + head_w * cos(perp), hy + head_w * sin(perp)
rx, ry = hx - head_w * cos(perp), hy - head_w * sin(perp)
color = COLORS.get(dst, "#0066cc")
# draw line segments, last one stops at head base
for i in range(len(pts) - 1):
x0, y0 = pts[i]
x1, y1 = pts[i + 1]
if i == len(pts) - 2:
x1, y1 = hx, hy
draw.line([(x0, y0), (x1, y1)], fill=color, width=arrow_w)
draw.polygon([(ax, ay), (lx, ly), (rx, ry)], fill=color)
lbl = label_for.get(dst, "")
if lbl:
mid_x = (pts[1][0] + pts[2][0]) / 2
mid_y = (pts[1][1] + pts[2][1]) / 2
pill(mid_x, mid_y, lbl, color)
img.save(OUT_PNG, "PNG", optimize=True)
img.save(OUT_JPG, "JPEG", quality=88, optimize=True, progressive=True)
print(f"\nwrote {OUT_PNG} ({img.size[0]}x{img.size[1]}px)")
print(f"wrote {OUT_JPG} ({img.size[0]}x{img.size[1]}px)")
async def main():
sizes = await capture_all()
compose(sizes)
if __name__ == "__main__":
asyncio.run(main())