vignette/apps/web/e2e/layout-visual-gate.spec.ts
2026-06-27 17:22:38 +09:00

293 lines
11 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { expect, test, type Page } from "@playwright/test";
import {
expectNoHorizontalOverflow,
fetchAvailablePersona,
signInAsLearner,
signInAsTeacher,
} from "./support";
/**
* Strict visual layout gate.
*
* The layout-redesign handoff (docs/ops/layout-redesign-handoff-2026-06-26.md)
* required a human-style visual acceptance pass across the redesigned screens at
* the suggested breakpoints. This spec hardens that pass into an automated gate:
* every redesigned screen is rendered at every required width, asserted free of
* horizontal overflow and clipped primary controls, and captured as a full-page
* screenshot artifact for review. Any single failure fails the whole gate.
*/
const GATE_WIDTHS = [
{ width: 390, height: 844, label: "390-mobile" },
{ width: 720, height: 900, label: "720-phablet" },
{ width: 861, height: 900, label: "861-tablet-min" },
{ width: 900, height: 900, label: "900-tablet" },
{ width: 1024, height: 768, label: "1024-tablet-land" },
{ width: 1280, height: 800, label: "1280-laptop" },
{ width: 1440, height: 900, label: "1440-desktop" },
] as const;
const SHOT_DIR = path.join(process.cwd(), "node_modules", ".tmp", "layout-gate");
async function ensureShotDir() {
await fs.mkdir(SHOT_DIR, { recursive: true });
}
interface ClipReport {
viewport: { width: number; height: number };
horizontalOverflow: number;
offenders: Array<{
tag: string;
role: string;
className: string;
text: string;
reason: string;
left: number;
right: number;
}>;
}
/**
* Scans every visible interactive control and prominent text container for
* either (a) extending beyond the viewport horizontally, or (b) clipping its own
* content (scrollWidth/scrollHeight exceeding the client box) — the two failure
* modes the redesign was meant to eliminate.
*/
async function auditClipping(page: Page): Promise<ClipReport> {
return page.evaluate(() => {
const doc = document.documentElement;
const viewport = { width: doc.clientWidth, height: window.innerHeight };
const selector = [
"button",
"a[href]",
"input",
"select",
"textarea",
"[role='tab']",
"[role='button']",
"[role='option']",
"h1",
"h2",
"h3",
".vg-btn",
].join(",");
// Walks ancestors to find the nearest box that clips overflow. Returns the
// clipping rect when that ancestor is NOT scrollable (i.e. content cut off,
// not reachable by scrolling). A scrollable carousel (overflow auto/scroll)
// legitimately holds off-screen children, so it is treated as non-clipping.
// X-axis only: offender detection compares horizontal edges, so only the
// horizontal overflow behaviour of ancestors matters. A horizontal carousel
// (overflow-x auto/scroll) holds reachable off-screen children and is fine;
// overflow-x hidden genuinely cuts content off.
function nearestHardClip(el: HTMLElement): DOMRect | null {
let node: HTMLElement | null = el.parentElement;
while (node && node !== document.body && node !== document.documentElement) {
const ox = window.getComputedStyle(node).overflowX;
if (ox === "auto" || ox === "scroll") return null; // reachable by scroll
if (ox === "hidden" || ox === "clip") return node.getBoundingClientRect();
node = node.parentElement;
}
return null;
}
const offenders: ClipReport["offenders"] = [];
const nodes = Array.from(document.querySelectorAll<HTMLElement>(selector));
for (const el of nodes) {
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
const visible =
style.display !== "none" &&
style.visibility !== "hidden" &&
Number(style.opacity) !== 0 &&
rect.width > 0 &&
rect.height > 0;
if (!visible) continue;
// Clipped by a hard (non-scrollable) overflow ancestor: content is cut off.
const clipRect = nearestHardClip(el);
const clippedByAncestor =
!!clipRect && (rect.right > clipRect.right + 1 || rect.left < clipRect.left - 1);
// Content clipping: the element cannot show its own text/children — but
// intentional truncation affordances (ellipsis, -webkit-line-clamp) are
// design choices the redesign uses for dense data, not defects.
const clipsX = style.overflowX === "hidden" || style.overflowX === "clip";
const clipsY = style.overflowY === "hidden" || style.overflowY === "clip";
const lineClamp =
style.getPropertyValue("-webkit-line-clamp") || (style as unknown as { webkitLineClamp?: string }).webkitLineClamp || "none";
const hasLineClamp = lineClamp !== "none" && lineClamp !== "" && lineClamp !== "0";
const hasEllipsis = style.textOverflow === "ellipsis";
// 폼 컨트롤(input/textarea/select)은 자기 값을 *설계상* 스크롤한다(커서/키보드로 전부
// 도달 가능). 박스보다 긴 값은 잘린 결함이 아니라 정상 스크롤 UX → ellipsis/line-clamp
// 와 같은 의도된 어포던스로 보고 text-clip 판정에서 제외(clipped-by-ancestor·가로 overflow는 유지).
const tagName = el.tagName.toLowerCase();
const isFormControl =
tagName === "input" || tagName === "textarea" || tagName === "select";
const textClippedX =
clipsX && !hasEllipsis && !isFormControl && Math.ceil(el.scrollWidth - el.clientWidth) > 1;
const textClippedY =
clipsY && !hasLineClamp && !isFormControl && Math.ceil(el.scrollHeight - el.clientHeight) > 1;
if (clippedByAncestor || textClippedX || textClippedY) {
const reasons: string[] = [];
if (clippedByAncestor) reasons.push("clipped-by-ancestor");
if (textClippedX) reasons.push("text-clipped-x");
if (textClippedY) reasons.push("text-clipped-y");
offenders.push({
tag: el.tagName.toLowerCase(),
role: el.getAttribute("role") ?? "",
className: String(el.className || "").slice(0, 80),
text: (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60),
reason: reasons.join(","),
left: Math.floor(rect.left),
right: Math.ceil(rect.right),
});
}
if (offenders.length >= 16) break;
}
return {
viewport,
horizontalOverflow: Math.ceil(doc.scrollWidth - doc.clientWidth),
offenders,
};
});
}
async function gateScreen(
page: Page,
screen: string,
prepareReady: () => Promise<void>,
) {
for (const vp of GATE_WIDTHS) {
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null))));
await prepareReady();
await expectNoHorizontalOverflow(page);
const report = await auditClipping(page);
expect(
report.horizontalOverflow,
`[${screen} @ ${vp.label}] horizontal overflow ${report.horizontalOverflow}px`,
).toBeLessThanOrEqual(1);
expect(
report.offenders,
`[${screen} @ ${vp.label}] clipped/overflowing controls: ${JSON.stringify(
report.offenders,
null,
2,
)}`,
).toEqual([]);
await page.screenshot({
path: path.join(SHOT_DIR, `${screen}__${vp.label}.png`),
fullPage: true,
});
}
}
test.describe("layout visual gate @single-run", () => {
test.describe.configure({ mode: "serial" });
test.beforeAll(async () => {
await ensureShotDir();
});
test("learner home stays contained and legible across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: {
email: `gate.learner.${Date.now()}@hs.ac.kr`,
role: "learner",
display_name: "이름이 아주 길게 표시되는 학습자 케이스 검증용 계정",
},
});
await page.request.post("/api/auth/consent", {
data: { accepted: true },
});
// Seed dense history: one active + two ended sessions.
const persona = await fetchAvailablePersona(page);
const made: string[] = [];
for (let i = 0; i < 3; i += 1) {
const res = await page.request.post("/api/sessions", {
data: { persona_code: persona.code, theory_mode: "humanistic" },
});
const body = (await res.json()) as { session_id: string };
made.push(body.session_id);
}
await page.request.post(`/api/sessions/${made[1]}/end`);
await page.request.post(`/api/sessions/${made[2]}/end`);
await page.goto("/learn");
await gateScreen(page, "learner-home", async () => {
await expect(page.locator(".lh-root")).toBeVisible({ timeout: 15_000 });
});
});
test("session prestart stays contained across all widths", async ({ page }) => {
await signInAsLearner(page);
const persona = await fetchAvailablePersona(page, 1);
await page.goto(`/learn/session/${persona.code}`);
await gateScreen(page, "session-prestart", async () => {
await expect(page.getByRole("button", { name: "회기 시작" })).toBeVisible({
timeout: 15_000,
});
});
});
test("active session keeps controls contained across all widths", async ({ page }) => {
await signInAsLearner(page);
const persona = await fetchAvailablePersona(page, 1);
await page.goto(`/learn/session/${persona.code}`);
await page.getByRole("button", { name: "회기 시작" }).click();
await expect(page.locator(".sx-page--active")).toBeVisible({ timeout: 15_000 });
await gateScreen(page, "session-active", async () => {
await expect(page.locator(".sx-page--active")).toBeVisible();
});
});
test("session review stays contained across all widths", async ({ page }) => {
await signInAsLearner(page);
const persona = await fetchAvailablePersona(page, 1);
const start = await page.request.post("/api/sessions", {
data: { persona_code: persona.code, theory_mode: "humanistic" },
});
const session = (await start.json()) as { session_id: string };
await page.request.post(`/api/sessions/${session.session_id}/end`);
await page.goto(`/learn/session/${session.session_id}/review`);
await gateScreen(page, "session-review", async () => {
await expect(page.locator(".sr-overview")).toBeVisible({ timeout: 15_000 });
});
});
test("professor console stays contained across all widths", async ({ page }) => {
await signInAsTeacher(page);
await page.goto("/teach");
await gateScreen(page, "professor", async () => {
await expect(page.locator(".pf-panel, .pf-shell, main").first()).toBeVisible({
timeout: 15_000,
});
});
});
test("admin console stays contained across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/admin");
await gateScreen(page, "admin", async () => {
await expect(page.locator("main").first()).toBeVisible({ timeout: 15_000 });
});
});
test("settings stays contained across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/settings");
await gateScreen(page, "settings", async () => {
await expect(page.locator("main").first()).toBeVisible({ timeout: 15_000 });
});
});
});