试验 React 内联上下文与原生表单登录流程

This commit is contained in:
2026-09-25 19:44:39 +00:00
parent 8c8b2ad352
commit dcf634d805
23 changed files with 2253 additions and 22 deletions
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<title>登录体验预览 · IAM</title>
</head>
<body>
<div id="root"></div>
<noscript>此预览使用 React 渲染页面,请启用 JavaScript。</noscript>
<script id="login-context" type="application/json">
__IAM_PAGE_CONTEXT__
</script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1280
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "iam-login-ui",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "tsc --noEmit && vite build",
"watch": "vite build --watch",
"test:browser": "playwright test"
},
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"vite": "8.3.1",
"typescript": "7.0.2",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@playwright/test": "1.63.0"
}
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: {
baseURL: process.env.IAM_PREVIEW_URL ?? "http://127.0.0.1:18081",
headless: true,
},
});
+159
View File
@@ -0,0 +1,159 @@
import { createRoot } from "react-dom/client";
import { useState, useLayoutEffect, type ReactNode } from "react";
import "./style.css";
type PageContext = {
step: "identity" | "verification" | "complete";
name: string;
error: string;
action: string;
csrf: { name: string; value: string };
};
const context: PageContext = JSON.parse(
document.getElementById("login-context")!.textContent!,
);
function Form({ children }: { children: ReactNode }) {
const [pending, setPending] = useState(false);
return (
<form
method="post"
action={context.action}
onSubmit={() => setPending(true)}
aria-busy={pending}
>
<input
type="hidden"
name={context.csrf.name}
value={context.csrf.value}
/>
{children}
<button className="primary" type="submit" disabled={pending}>
{pending
? "正在继续…"
: context.step === "complete"
? "重新体验"
: "继续"}
</button>
</form>
);
}
function App() {
useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []);
const [showHelp, setShowHelp] = useState(false);
return (
<main>
<header>
<a href="/preview" className="brand" aria-label="IAM 登录体验预览">
i<span>am</span>
<span className="badge">预览</span>
</a>
</header>
<section className="card" aria-labelledby="title">
<div className="eyebrow">登录交互原型</div>
<ol className="steps" aria-label="当前步骤">
{(["identity", "verification", "complete"] as const).map(
(step, i) => (
<li
key={step}
aria-current={context.step === step ? "step" : undefined}
>
<span>{i + 1}</span>
{["填写称呼", "模拟验证", "完成"][i]}
</li>
),
)}
</ol>
{context.step === "identity" && (
<>
<h1 id="title">从这里开始</h1>
<p className="intro">
体验一次完整的页面切换。先告诉我们怎么称呼你。
</p>
</>
)}
{context.step === "verification" && (
<>
<h1 id="title">你好,{context.name}</h1>
<p className="intro">
这是第二步页面。输入演示码 <strong>123456</strong>{" "}
继续,也可以试试输入错误的演示码。
</p>
</>
)}
{context.step === "complete" && (
<>
<div className="success" aria-hidden="true">
✓
</div>
<h1 id="title">体验完成</h1>
<p className="intro">
{context.name}
,你已走完页面预览。这没有建立登录身份,也没有向任何应用授权。
</p>
</>
)}
{context.error && (
<p className="error" role="alert">
{context.error}
</p>
)}
<Form>
{context.step === "identity" && (
<label>
称呼
<input
name="name"
autoComplete="off"
autoFocus
required
maxLength={64}
placeholder="例如:小潘"
defaultValue={context.name}
/>
</label>
)}
{context.step === "verification" && (
<label>
演示码
<input
name="code"
inputMode="numeric"
autoComplete="off"
autoFocus
required
maxLength={6}
pattern="[0-9]{6}"
placeholder="123456"
aria-invalid={Boolean(context.error)}
/>
</label>
)}
</Form>
{context.step === "verification" && (
<a className="back" href="/preview">
返回上一步
</a>
)}
<div className="help">
<button
type="button"
className="link"
aria-expanded={showHelp}
onClick={() => setShowHelp(!showHelp)}
>
这是真实登录吗?
</button>
{showHelp && (
<p>不是。这里仅演示页面交互,请勿输入真实密码或 MFA 验证码。</p>
)}
</div>
</section>
<footer>独立 IAM · 页面体验预览</footer>
</main>
);
}
createRoot(document.getElementById("root")!).render(<App />);
+240
View File
@@ -0,0 +1,240 @@
:root {
font-family: Inter, "Noto Sans SC", system-ui, sans-serif;
color: #182826;
background: #f3f5f1;
font-synthesis: none;
font-size: 16px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
main {
max-width: 520px;
margin: 0 auto;
padding: 40px 20px 28px;
}
header {
margin-bottom: 40px;
}
.brand {
font-size: 32px;
font-weight: 750;
letter-spacing: -2px;
color: #285448;
text-decoration: none;
}
.brand > span:first-child {
font-weight: 400;
}
.badge {
font-size: 11px;
letter-spacing: 1px;
vertical-align: middle;
margin-left: 14px;
padding: 5px 8px;
border: 1px solid #b7c9be;
border-radius: 5px;
}
.card {
background: #fff;
border: 1px solid #dce4dd;
border-radius: 18px;
padding: 36px;
box-shadow: 0 12px 40px #173f2510;
}
.eyebrow {
font-size: 12px;
color: #60746a;
letter-spacing: 2px;
}
.steps {
display: flex;
justify-content: space-between;
padding: 0;
list-style: none;
margin: 25px 0 32px;
gap: 8px;
}
.steps li {
font-size: 12px;
color: #718078;
display: flex;
align-items: center;
gap: 7px;
}
.steps li span {
display: inline-grid;
place-items: center;
width: 23px;
height: 23px;
border: 1px solid #ccd7ce;
border-radius: 50%;
font-size: 11px;
}
.steps [aria-current] {
color: #215542;
font-weight: 650;
}
.steps [aria-current] span {
background: #215542;
color: white;
border-color: #215542;
}
h1 {
font-size: 27px;
letter-spacing: -0.5px;
line-height: 1.35;
margin: 0 0 12px;
overflow-wrap: anywhere;
}
.intro {
font-size: 14px;
color: #60716a;
line-height: 1.8;
margin: 0 0 25px;
}
label {
display: block;
font-size: 14px;
font-weight: 600;
}
input:not([type="hidden"]) {
display: block;
width: 100%;
border: 1px solid #bdccc1;
border-radius: 8px;
padding: 13px 14px;
margin: 9px 0 22px;
font: inherit;
color: inherit;
background: #fff;
}
input:focus {
outline: 3px solid #a9cbbc;
outline-offset: 2px;
}
button {
font: inherit;
cursor: pointer;
}
.primary {
width: 100%;
border: 0;
background: #245b47;
color: #fff;
font-weight: 600;
border-radius: 8px;
padding: 13px;
}
.primary:hover {
background: #194734;
}
.primary:disabled {
opacity: 0.65;
cursor: wait;
}
.error {
color: #9e302b;
background: #fff0ed;
padding: 12px;
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
}
.back {
display: block;
text-align: center;
font-size: 13px;
margin-top: 18px;
color: #476a58;
}
.help {
border-top: 1px solid #e5ebe6;
margin-top: 28px;
padding-top: 20px;
}
.link {
background: none;
border: 0;
color: #5b7064;
padding: 0;
font-size: 13px;
}
.help p {
font-size: 13px;
line-height: 1.8;
color: #6a756e;
margin-bottom: 0;
}
footer {
text-align: center;
color: #7c887e;
font-size: 12px;
margin-top: 28px;
}
.success {
color: #245b47;
font-size: 30px;
margin-bottom: 12px;
}
a:focus-visible,
button:focus-visible {
outline: 3px solid #a9cbbc;
outline-offset: 3px;
}
@media (max-width: 480px) {
main {
padding-top: 24px;
}
header {
margin-bottom: 24px;
}
.card {
padding: 26px 22px;
}
.steps {
gap: 5px;
}
.steps li {
font-size: 11px;
}
}
@media (prefers-color-scheme: dark) {
:root {
background: #14221c;
color: #edf4ee;
}
.card {
background: #1e3027;
border-color: #344b3d;
}
.brand,
.steps [aria-current],
.success {
color: #b9ddc8;
}
.intro,
.eyebrow,
.help p,
.link,
.back {
color: #acbfb2;
}
.steps li {
color: #98aa9e;
}
input:not([type="hidden"]) {
background: #18271f;
border-color: #526657;
}
.help {
border-color: #3a4d40;
}
.error {
background: #492b29;
color: #ffc3b9;
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+95
View File
@@ -0,0 +1,95 @@
import { test, expect } from "@playwright/test";
test("原生 POST 逐页导航,内联上下文,浏览器缓存静态资源", async ({ page }) => {
const xhr: string[] = [];
const posts: string[] = [];
const errors: string[] = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (req) => {
if (["fetch", "xhr"].includes(req.resourceType())) xhr.push(req.url());
if (req.method() === "POST" && req.isNavigationRequest())
posts.push(req.url());
});
await page.goto("/preview");
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
const scriptUrl = await page.locator("script[src]").getAttribute("src");
await page.getByRole("button", { name: "这是真实登录吗?" }).click();
await expect(page.getByText("不是。这里仅演示页面交互")).toBeVisible();
await page.getByLabel("称呼").fill("预览用户");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page).toHaveURL(/\/preview\/verify$/);
await expect(
page.getByRole("heading", { name: "你好,预览用户" }),
).toBeVisible();
await page.getByLabel("演示码").fill("000000");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("alert")).toContainText("演示码不正确");
await page.getByLabel("演示码").fill("123456");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading", { name: "体验完成" })).toBeVisible();
expect(posts).toHaveLength(3);
expect(xhr).toEqual([]);
expect(errors).toEqual([]);
const timing = await page.evaluate(() => ({
navigation: performance
.getEntriesByType("navigation")
.map((e) => e.toJSON()),
resources: performance.getEntriesByType("resource").map((e) => e.toJSON()),
}));
const script = timing.resources.find((r) => r.name.endsWith(scriptUrl!));
expect(script?.transferSize).toBe(0);
await test
.info()
.attach("navigation-and-cache.json", {
body: JSON.stringify(timing, null, 2),
contentType: "application/json",
});
expect(
(
await page.request.get("/", { headers: { Accept: "application/json" } })
).status(),
).toBe(401);
await page.getByRole("button", { name: "重新体验" }).click();
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
});
test("移动端与脚本结束标记作为纯文本显示", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/preview");
const name = "</script><script>window.__injected=1</script>";
await page.getByLabel("称呼").fill(name);
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading")).toHaveText(`你好,${name}`);
expect(
await page.evaluate(() => Reflect.get(window, "__injected")),
).toBeUndefined();
expect(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
).toBe(true);
await page.screenshot({ path: "test-results/mobile.png", fullPage: true });
});
test("受限网络下首屏和缓存后页面切换计时", async ({ page, context }) => {
const cdp = await context.newCDPSession(page);
await cdp.send("Network.enable");
await cdp.send("Network.emulateNetworkConditions", {
offline: false, latency: 60, downloadThroughput: 1_500_000 / 8,
uploadThroughput: 750_000 / 8,
});
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
await page.goto("/preview");
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
const cold = await page.evaluate(() => performance.getEntriesByName("iam-page-ready")[0].startTime);
await page.getByLabel("称呼").fill("计时体验");
const start = performance.now();
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading", { name: "你好,计时体验" })).toBeVisible();
const warm = performance.now() - start;
const result = { network_latency_ms: 60, download_mbps: 1.5, cpu_slowdown: 4,
cold_navigation_to_react_commit_ms: Math.round(cold), warm_click_to_visible_ms: Math.round(warm) };
console.log(JSON.stringify(result));
await test.info().attach("timing.json", { body: JSON.stringify(result, null, 2), contentType: "application/json" });
});
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}
+6
View File
@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
export default defineConfig({
base: "/",
build: { outDir: "dist", emptyOutDir: true },
});