vignette/apps/web/e2e/layout-visual-gate.spec.ts
2026-07-01 12:41:17 +09:00

647 lines
25 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { expect, test, type Page } from "@playwright/test";
import {
EMPTY_REVIEW_SESSION_ID,
FILLED_REVIEW_SESSION_ID,
routeEmptySessionReview,
routeFilledSessionReview,
routePrepostMeasures,
} from "./session-review-fixture";
import {
completeOnboarding,
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");
const TEACHER_REVIEW_SESSION_ID = "teacher-review-visual";
function teacherAnalysisFixture() {
const learnerId = "visual-analysis-learner";
const sessions = Array.from({ length: 5 }, (_unused, index) => {
const sessionNo = index + 1;
return {
session_id: `${learnerId}-session-${sessionNo}`,
learner_id: learnerId,
learner_label: "분석 검증 학습자",
persona_code: sessionNo % 2 === 0 ? "P2" : "P1",
persona_name: sessionNo % 2 === 0 ? "민재" : "서연",
session_no: sessionNo,
status: "ended",
stage: sessionNo >= 4 ? "개입" : "탐색",
turn_count: 8 + sessionNo,
learner_turn_count: 4 + sessionNo,
client_turn_count: 4,
started_at: `2026-06-${String(10 + sessionNo).padStart(2, "0")}T09:00:00Z`,
ended_at: `2026-06-${String(10 + sessionNo).padStart(2, "0")}T09:30:00Z`,
review_status: sessionNo === 3 ? "closed" : "pending",
review_note: null,
reviewed_at: sessionNo === 3 ? "2026-06-13T10:00:00Z" : null,
};
});
const points = sessions.map((session) => ({
session_id: session.session_id,
session_no: session.session_no,
persona_code: session.persona_code,
stage: session.stage,
started_at: session.started_at,
ended_at: session.ended_at,
score: session.session_no >= 4 ? 0.88 : 0.52,
rapport: Math.min(0.8, session.session_no * 0.12),
technique_count: session.session_no + 1,
watch_count: session.session_no < 4 ? 1 : 0,
}));
const summary = {
learner_id: learnerId,
learner_label: "분석 검증 학습자",
sessions: sessions.length,
ended_sessions: sessions.length,
latest_at: sessions[sessions.length - 1].ended_at ?? "",
first_score: points[0].score,
latest_score: points[points.length - 1].score,
score_delta: (points[points.length - 1].score ?? 0) - (points[0].score ?? 0),
avg_score: 0.72,
avg_rapport: 0.44,
trend: "up",
top_techniques: ["reflection", "summary"],
points,
};
return {
dashboard: {
source: "database",
cohort_label: "Visual cohort",
total_learners: 1,
active_sessions: 0,
ended_sessions: sessions.length,
learner_growth: [{ ...summary, points: points.slice(-4) }],
safety_alerts: [],
pending_reviews: [],
recent_sessions: sessions.slice(-2),
message: "학생 분석 시각 검증 fixture.",
},
analysis: {
source: "database",
learner_id: learnerId,
learner_label: "분석 검증 학습자",
total_sessions: sessions.length,
ended_sessions: sessions.length,
active_sessions: 0,
pending_reviews: 2,
summary,
points,
stage_breakdown: [
{ stage: "라포", sessions: 0, turns: 0 },
{ stage: "탐색", sessions: 3, turns: 31 },
{ stage: "개입", sessions: 2, turns: 22 },
{ stage: "정리", sessions: 0, turns: 0 },
],
sessions,
message: "분석 검증 학습자 전체 회기 5건",
},
};
}
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 expect(
page.locator("html"),
`[${screen} @ ${vp.label}] layout gate must capture the dark UI surface`,
).toHaveAttribute("data-theme", "dark");
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,
});
}
}
async function expectEmptyReviewNoDeadThirdColumn(page: Page) {
const report = await page.evaluate(() => {
const root = document.querySelector<HTMLElement>(".sr-root--empty");
const cols = document.querySelector<HTMLElement>(".sr-root--empty .sr-cols");
const transcript = document.querySelector<HTMLElement>(".sr-card--transcript");
if (!root || !cols || !transcript) {
return {
present: false,
columnCount: 0,
};
}
const gridTemplate = getComputedStyle(cols).gridTemplateColumns;
const columnCount = gridTemplate.split(" ").filter(Boolean).length;
const transcriptRect = transcript.getBoundingClientRect();
return {
present: true,
columnCount,
transcriptWidth: Math.round(transcriptRect.width),
mainColumnWidth: Math.round(cols.getBoundingClientRect().width),
};
});
expect(report.present, "empty review layout should be mounted").toBe(true);
expect(
report.columnCount,
"empty review should collapse the desktop masonry layout instead of leaving a sparse third column",
).toBeLessThanOrEqual(2);
}
async function expectFilledReviewLearnerWorkbench(page: Page) {
const report = await page.evaluate(() => {
const cols = document.querySelector<HTMLElement>(".sr-cols--learner");
const transcript = document.querySelector<HTMLElement>(".sr-card--transcript");
const overview = document.querySelector<HTMLElement>(".sr-overview");
const rubric = document.querySelector<HTMLElement>(".sr-card--rubric");
const worksheet = document.querySelector<HTMLElement>(".sr-card--worksheet");
const prepost = document.querySelector<HTMLElement>(".sr-card--prepost");
if (!cols || !transcript || !overview || !rubric || !worksheet || !prepost) {
return {
present: false,
viewportWidth: window.innerWidth,
columnCount: 0,
overviewRight: 0,
transcriptLeft: 0,
transcriptRight: 0,
rubricLeft: 0,
worksheetLeft: 0,
worksheetRight: 0,
prepostLeft: 0,
};
}
const columnCount = getComputedStyle(cols).gridTemplateColumns.split(" ").filter(Boolean).length;
const transcriptRect = transcript.getBoundingClientRect();
const overviewRect = overview.getBoundingClientRect();
const rubricRect = rubric.getBoundingClientRect();
const worksheetRect = worksheet.getBoundingClientRect();
const prepostRect = prepost.getBoundingClientRect();
return {
present: true,
viewportWidth: window.innerWidth,
columnCount,
overviewRight: Math.ceil(overviewRect.right),
transcriptLeft: Math.floor(transcriptRect.left),
transcriptRight: Math.ceil(transcriptRect.right),
rubricLeft: Math.floor(rubricRect.left),
worksheetLeft: Math.floor(worksheetRect.left),
worksheetRight: Math.ceil(worksheetRect.right),
prepostLeft: Math.floor(prepostRect.left),
};
});
expect(report.present, "filled learner review layout should be mounted").toBe(true);
if (report.viewportWidth > 1180) {
expect(report.columnCount, "desktop learner review should use a 3-column workbench").toBe(3);
expect(report.overviewRight).toBeLessThanOrEqual(report.transcriptLeft);
expect(report.transcriptRight).toBeLessThanOrEqual(report.rubricLeft);
expect(report.worksheetLeft).toBeLessThan(report.transcriptLeft);
expect(report.worksheetRight).toBeLessThanOrEqual(report.prepostLeft);
}
}
async function expectSupervisorReviewNoDeadGaps(page: Page) {
const report = await page.evaluate(() => {
const cols = document.querySelector<HTMLElement>(".sr-cols--supervisor");
const left = document.querySelector<HTMLElement>(".sr-cols--supervisor .sr-left");
const right = document.querySelector<HTMLElement>(".sr-cols--supervisor .sr-right");
if (!cols || !left || !right) {
return {
present: false,
viewportWidth: window.innerWidth,
columnCount: 0,
leftDisplay: "",
rightDisplay: "",
maxMainGap: 0,
maxSideGap: 0,
};
}
function maxVerticalGap(container: HTMLElement) {
const intervals = Array.from(container.children)
.map((child) => child.getBoundingClientRect())
.filter((rect) => rect.width > 0 && rect.height > 0)
.map((rect) => ({ top: rect.top, bottom: rect.bottom }))
.sort((a, b) => a.top - b.top || a.bottom - b.bottom);
if (intervals.length < 2) return 0;
let maxGap = 0;
let currentBottom = intervals[0].bottom;
for (let index = 1; index < intervals.length; index += 1) {
const next = intervals[index];
if (next.top <= currentBottom) {
currentBottom = Math.max(currentBottom, next.bottom);
continue;
}
const gap = next.top - currentBottom;
if (gap > maxGap) maxGap = gap;
currentBottom = next.bottom;
}
return Math.round(maxGap);
}
const colsStyle = getComputedStyle(cols);
const leftStyle = getComputedStyle(left);
const rightStyle = getComputedStyle(right);
return {
present: true,
viewportWidth: window.innerWidth,
columnCount: colsStyle.gridTemplateColumns.split(" ").filter(Boolean).length,
leftDisplay: leftStyle.display,
rightDisplay: rightStyle.display,
maxMainGap: maxVerticalGap(left),
maxSideGap: maxVerticalGap(right),
};
});
expect(report.present, "supervisor review layout should be mounted").toBe(true);
if (report.viewportWidth > 1180) {
expect(report.columnCount, "desktop supervisor review should use main + review rail").toBe(2);
expect(report.leftDisplay).toBe("grid");
expect(report.rightDisplay).toBe("grid");
expect(
report.maxMainGap,
"desktop supervisor review main column should not leave a dead vertical void",
).toBeLessThanOrEqual(40);
expect(
report.maxSideGap,
"desktop supervisor review side rail should not leave a dead vertical void",
).toBeLessThanOrEqual(40);
}
}
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 completeOnboarding(page, {
legal_name: "이름이 아주 길게 표시되는 학습자 케이스 검증용 계정",
affiliation: "한신대학교",
department: "상담심리학과",
grade_level: "4학년",
phone: "010-3333-3333",
contact_address: "경기도 오산시 한신대학교",
});
// 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 });
await expect(page.locator(".lh-dashboard-status .lh-metric-card").first()).toBeVisible({
timeout: 15_000,
});
await expect(page.locator(".lh-work-cluster")).toBeVisible({ timeout: 15_000 });
await expect(page.locator(".lh-compact-list li").first()).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);
await routeFilledSessionReview(page);
await routePrepostMeasures(page);
await page.goto(`/learn/session/${FILLED_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review", async () => {
await expect(page.locator(".sr-overview")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("사례개념화 워크시트")).toBeVisible();
await expectFilledReviewLearnerWorkbench(page);
});
});
test("professor session review avoids dead vertical gaps across all widths", async ({ page }) => {
await signInAsTeacher(page);
await routeFilledSessionReview(page, TEACHER_REVIEW_SESSION_ID);
await page.goto(`/teach/session/${TEACHER_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review-professor", async () => {
await expect(page.locator(".sr-cols--supervisor")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("교수자 검토", { exact: true })).toBeVisible();
await expect(page.getByText("세션 트랜스크립트")).toBeVisible();
await expectSupervisorReviewNoDeadGaps(page);
});
});
test("empty session review avoids sparse column gaps across all widths", async ({ page }) => {
await signInAsLearner(page);
await routeEmptySessionReview(page);
await routePrepostMeasures(page);
await page.goto(`/learn/session/${EMPTY_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review-empty", async () => {
await expect(page.locator(".sr-root--empty")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("축어록 저장 후 생성")).toBeVisible();
await expect(page.getByText("감정 타임라인 대기")).toBeVisible();
await expectEmptyReviewNoDeadThirdColumn(page);
});
});
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("professor student analysis overview stays contained across all widths", async ({ page }) => {
const fixture = teacherAnalysisFixture();
await page.route("**/api/teacher/dashboard", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.dashboard),
}),
);
await signInAsTeacher(page);
await page.goto("/teach/analysis");
await gateScreen(page, "professor-analysis", async () => {
await expect(page.locator('[data-learner-overview-table="true"]')).toBeVisible({
timeout: 15_000,
});
await expect(page.locator('[data-learner-overview-row="true"]')).toHaveCount(1);
await expect(page.locator('[data-learner-analysis-panel="true"]')).toHaveCount(0);
await expect(page.getByLabel("학습자 검색")).toBeVisible();
const expandButton = page.getByRole("button", { name: /분석 검증 학습자 요약/ });
if ((await expandButton.getAttribute("aria-expanded")) !== "true") {
await expandButton.click();
}
await expect(page.locator('[data-learner-expanded-row="true"]')).toBeVisible();
});
});
test("professor learner detail analysis stays contained across all widths", async ({ page }) => {
const fixture = teacherAnalysisFixture();
await page.route("**/api/teacher/dashboard", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.dashboard),
}),
);
await page.route("**/api/teacher/learners/*/analysis", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.analysis),
}),
);
await signInAsTeacher(page);
await page.goto(`/teach/analysis?learner=${fixture.analysis.learner_id}`);
await gateScreen(page, "professor-analysis-detail", async () => {
await expect(page.locator('[data-learner-analysis-panel="true"]')).toBeVisible({
timeout: 15_000,
});
await page.getByRole("tab", { name: /^전체 회기/ }).click();
await expect(page.locator('[data-learner-session-row="true"]')).toHaveCount(5);
});
});
test("persona studio stays contained across all widths", async ({ page }) => {
await signInAsTeacher(page);
await page.goto("/teach/personas");
await gateScreen(page, "persona-studio", async () => {
await expect(page.locator(".ps-layout")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("내담자 설계·검수 작업면")).toBeVisible();
await page.getByRole("tab", { name: "프롬프트" }).click();
const promptPreview = page.getByLabel("프롬프트 미리보기");
await expect(promptPreview).toBeVisible();
await expect(promptPreview.getByRole("textbox")).toHaveCount(0);
});
});
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 });
});
});
});