深入解读 modern-web-guidance:light-dismiss 对话框的验收标准与实现原理
深入解读 modern-web-guidance:light-dismiss 对话框的验收标准与实现原理
在 modern-web-guidance 仓库中,guides/ui-behaviors/light-dismiss-a-dialog 这个用例用一份只有 8 行的 expectations.md 精确定义了"点击遮罩关闭模态框"这一交互的验收边界。本文以这份验收标准为骨架,结合同一目录下的参考实现、Playwright 评分器与仓库中的对话框总指南,逐条拆解每条期望的技术含义、实现要点和容易踩的坑,最终给出可直接复用的完整代码与自检清单。
一、这份 expectations.md 在仓库中扮演什么角色
在 modern-web-guidance 的用例目录结构里,一个完整的指导单元通常由四个文件构成,它们职责分明:
| 文件 | 作用 | 本文对象 |
|---|---|---|
guide.md |
面向人与编码 Agent 的技术指导正文,包含强制性规则(MANDATORY / DO / DO NOT) | 参考骨架 |
expectations.md |
把指导正文压缩成可判定的验收条目,每条都应能被自动化测试覆盖 | 本文主体 |
grader.ts |
Playwright 评分脚本,逐条落地 expectations.md 的断言 |
验证手段 |
demo.html / negative-demo.html |
正例与反例实现 | 直观对照 |
对应文件分别为 expectations.md、guide.md、grader.ts、demo.html 与 negative-demo.html。
原文 expectations.md 的全部八条如下,这是本文必须完整继承的最小信息集:
<dialog>元素必须带有closedby="any"属性。<dialog>应通过aria-labelledby、aria-label或同类方式拥有可访问名称。- 点击触发按钮或链接时,必须使用
showModal()方法打开对话框。 - 点击遮罩(对话框内容之外的区域)必须关闭对话框。
- 按下
Esc键必须关闭对话框。 - 点击对话框内部的关闭或取消按钮必须关闭对话框。
- 点击对话框内容区域(而非遮罩)不应关闭对话框。
- 实现必须为不支持
closedby属性的浏览器提供 light-dismiss 的降级机制。
值得注意的是,expectations.md 在仓库工作流中并非"随手写的备注"。在 src/authoring/dev-prompts.ts 里明确要求"expectations.md 中的每个顶层期望必须至少有一条专门的测试覆盖",且当评分校准失败时以 guide.md 为准来裁剪或放宽 expectations.md。这意味着这份 8 条清单既是实现契约,也是测试用例的生成依据。
此外,用例的元信息标注了它依赖的 Web 平台特性 ID:
name: light-dismiss-a-dialog
description: Create a modal dialog that can be closed via light dismiss (i.e. clicking or tapping outside of the dialog)
web-feature-ids:
- dialog-closedby
这个 dialog-closedby 会在正文中以 {{ BASELINE_STATUS("dialog-closedby") }} 宏的形式出现,构建时由 src/core/macros.ts 中的 BASELINE_STATUS 处理器替换为真实的 Baseline 状态文案,而不是手写"某浏览器不支持"之类的易过期描述。
二、逐条拆解八项验收标准
2.1 第 1 条:必须声明 closedby="any"
<dialog id="lightDismissDialog" closedby="any" aria-labelledby="dialogTitle">
closedby 是让"点击遮罩关闭"变成声明式行为的唯一开关。页面不需要任何 JavaScript 事件监听,浏览器原生负责把遮罩上的点击转换为一次关闭请求。为什么必须是 any 而不是留空?因为模态对话框的默认值等价于 closerequest,它只响应 Esc、移动端返回手势等"关闭请求",并不包含遮罩点击。
三种取值的完整语义(摘自 guide.md 的 Attribute Values 小节,并结合 guides/ui-components/dialog/guide.md 的关闭策略章节):
| 取值 | 遮罩点击(light dismiss) | 关闭请求(Esc、返回手势) |
开发者 dialog.close() |
典型场景 |
|---|---|---|---|---|
any |
关闭 | 关闭 | 关闭 | 提示框、快速预览、二次确认弹层 |
closerequest |
不关闭 | 关闭 | 关闭 | 模态默认值,不希望误触关闭 |
none |
不关闭 | 不关闭 | 关闭 | 含未保存改动的表单,需显式确认 |
如果属性缺失或取值非法,showModal() 打开时按 closerequest 处理,其他方式打开时按 none 处理。这一点在对话框总指南中被明确写出,是判断"到底该不该加属性"的依据。
2.2 第 2 条:可访问名称不可省略
验收条目用的是 "should" 而非 "must",但在评分器里它是一条独立的硬断言:读取 aria-label,或读取 aria-labelledby 指向的元素是否真实存在。
const hasLabel = await dialog.evaluate(el => {
const label = el.getAttribute('aria-label');
const labeledBy = el.getAttribute('aria-labelledby');
return !!(label || (labeledBy && document.getElementById(labeledBy)));
});
这里有一个容易被忽略的细节:aria-labelledby 指向的 ID 必须能在文档中找到。只写 aria-labelledby="dialogTitle" 却把标题元素漏掉,断言会直接失败。推荐做法是让 ID 直接挂到对话框内的标题元素上:
<dialog id="lightDismissDialog" closedby="any" aria-labelledby="dialogTitle">
<h2 id="dialogTitle">Welcome!</h2>
</dialog>
同时,总指南强调不要再给原生模态框追加 role="dialog" 或 aria-modal,浏览器已经提供这些语义,重复声明反而可能引入冲突。
2.3 第 3 条:必须用 showModal() 打开
这一条包含两层含义:调用方式必须是 showModal(),效果上必须真正进入模态状态。
openButton.addEventListener('click', () => {
dialog.showModal();
});
评分器没有停留在"有 open 属性"这种弱检查上,而是进一步验证 :modal 伪类是否匹配:
const isModal = await dialog.evaluate(el => (el as HTMLDialogElement).matches(':modal'));
expect(isModal).toBe(true);
原因很实际:dialog.show() 也会让 open 属性存在,但它打开的是非模态对话框——没有 ::backdrop、没有焦点陷阱、页面其他内容仍可交互。只有 showModal() 才会把元素提升到 top layer,产生遮罩并让页面其余部分进入惰性状态。
顺带一提,closedby 与 showModal() 是强绑定的组合。guide.md 的约束里明确写着 DO NOT 对用 show() 打开的非模态对话框使用 closedby,因为根本没有遮罩可供点击,light-dismiss 无从触发。
2.4 第 4 条:点击遮罩必须关闭
这是整套期望的核心。在浏览器实现层面,遮罩由 ::backdrop 伪元素渲染,它覆盖整个视口并位于对话框正后方;对它的点击会被浏览器合成为一次对 <dialog> 元素本身的点击事件,因此事件目标 event.target === dialog。closedby="any" 让浏览器把这个信号翻译成关闭动作。
评分器用最直接的方式验证:打开对话框后把鼠标点到视口左上角(明显位于遮罩区域),然后断言 open 属性消失。
await page.mouse.click(10, 10);
await expect(dialog).not.toHaveAttribute('open', { timeout: 2000 });
这里给了一个重要的实现提示:不要把对话框做成铺满视口的全屏容器,否则"内容区域"与"遮罩区域"边界消失,用户再也点不到遮罩,第 4 条与第 7 条会互相矛盾。
2.5 第 5 条:Esc 必须关闭
Esc 是模态对话框自带的关闭请求通道,即使完全没有 closedby 属性也存在。测试直接按键并断言关闭:
await page.keyboard.press('Escape');
await expect(dialog).not.toHaveAttribute('open', { timeout: 2000 });
guide.md 对这一条补充了一个容易被忽略的耦合风险:如果对话框内部嵌入了自身使用 Esc 的组件(例如菜单、组合框、搜索建议),必须确保这些组件在获得焦点时捕获并消费 Esc,否则用户只是想收起下拉菜单,整个对话框却被一并关掉。这是"页面看起来正常、键盘用户却痛苦"的典型来源。
2.6 第 6 条:内部关闭按钮必须关闭
参考实现用最朴素也最可靠的方式:把按钮放进 method="dialog" 的表单里。
<form method="dialog">
<button type="submit">Close</button>
</form>
表单提交即触发对话框关闭,无需一行脚本。评分器会按文本匹配 Close 或 Cancel 的按钮或链接:
const closeButton = dialog.locator('button, a').filter({ hasText: /(Close|Cancel)/i }).first();
这也解释了 guide.md 中的 DO:永远保留一个可见的关闭按钮。遮罩点击与 Esc 都是"快捷方式",但触屏、键盘导航和辅助技术用户需要一个明确、可聚焦、有可访问名称的关闭控件。原生 <button> 的可访问名称来自文本内容,比自制的 div 关闭图标稳妥得多。
2.7 第 7 条:点击内容区域不能关闭
遮挡的反面是误关。测试在对话框内部的标题或段落上点击,断言对话框仍然打开:
const content = dialog.locator('h2, p').first();
await content.click();
await expect(dialog).toHaveAttribute('open', '');
这条期望看起来平凡,实际是最容易在降级实现中出错的一条。若降级脚本仅用 event.target !== dialog 做判断,就会出现两类误判:
- 点击对话框自身的
padding区域时,event.target确实等于dialog(内边距属于元素本身),会被误判为"点在遮罩上"而关闭; - 点击子元素之间的空白缝隙(例如 flex 布局的
gap)时,event.target同样是dialog,也会被误关。
因此正确做法不能只信 event.target,必须结合几何坐标判断指针是否落在对话框内容盒内。这正是第 8 条降级脚本里 getBoundingClientRect() 存在的原因。
2.8 第 8 条:必须提供降级机制
这是八条中唯一明确写 "MANDATORY" 的实现要求。检测手段是特性检测而非 UA 嗅探,注意属性名是驼峰形式的 closedBy(DOM 属性),与 HTML 属性 closedby 对应:
if (!('closedBy' in HTMLDialogElement.prototype)) {
// 安装降级逻辑
}
guide.md 给出的参考脚本如下:
const dialog = document.querySelector('dialog');
// Fallback for browsers without closedby support
if (!('closedBy' in HTMLDialogElement.prototype)) {
dialog.addEventListener('click', (event) => {
// 1. When clicking the backdrop, the event target is the dialog element itself.
// Ignore clicks where the target is a child element inside the dialog.
if (event.target !== dialog) return;
// 2. Check if the click coordinates fall within the dialog's content box.
// This distinguishes between a click on the backdrop vs a click on the dialog's background/padding.
const rect = dialog.getBoundingClientRect();
const isDialogContent = (
rect.top <= event.clientY &&
event.clientY <= rect.top + rect.height &&
rect.left <= event.clientX &&
event.clientX <= rect.left + rect.width
);
if (isDialogContent) return;
// 3. Since the click was outside the content area (on the backdrop), manually close the dialog.
dialog.close();
});
}
评分器对这条的验证方式比较"文本化"——扫描页面所有内联脚本,确认同时出现了 getBoundingClientRect 与 .close():
const scriptContent = scripts.map(s => s.textContent).join(' ');
return scriptContent.includes('getBoundingClientRect') && scriptContent.includes('.close()');
这提醒我们:降级逻辑必须内联写在页面脚本中(或至少在测试可读取的 script 内容里),如果打包进外部模块文件,这种基于页面脚本内容的检查就看不到它。
三、一个更严格的降级版本
guides/ui-components/dialog/guide.md 的 Fallback 章节给出了一版比上面更健壮的实现,值得对照学习。它做了三点改进:
if (!('closedBy' in HTMLDialogElement.prototype)) {
const outside = (e, dialog) => {
const r = dialog.getBoundingClientRect();
return e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom;
};
for (const dialog of document.querySelectorAll('dialog[closedby="any"]')) {
let pressedOutside = false;
dialog.addEventListener('pointerdown', (e) => { pressedOutside = outside(e, dialog); });
// Require the press and the release outside, so a text-selection drag that ends on the backdrop does not dismiss
dialog.addEventListener('pointerup', (e) => { if (pressedOutside && outside(e, dialog)) dialog.close(); });
}
}
改进点一:完全依赖坐标而不是 event.target。注释里写得很清楚——<dialog> 同时也是其自身 padding 和子元素之间空隙的事件目标,纯 target 判断会在这些位置误关闭。
改进点二:批量选择 dialog[closedby="any"],而不是只取 document.querySelector('dialog'),页面里存在多个对话框时不会漏装。
改进点三:要求按下与抬起都发生在外部。用户在对话框内选中文本,拖拽到遮罩上松手,如果只看 pointerup 就会意外关闭;用 pointerdown 记录起始位置再配合 pointerup 复核,才能区分"拖选结束"与"点击外部"。
选择哪一版取决于你的验收严格度:expectations.md 只要求存在几何检查的降级;而对话框总指南面向的是生产级最佳实践。二者并不冲突,取更严格的实现即可同时满足。
四、完整可运行参考实现
把前面各条拼起来,得到一个同时满足八条验收标准的最小页面(结构与 demo.html 一致):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Light Dismiss Dialog Demo</title>
<style>
body {
font-family: system-ui, sans-serif;
padding: 2rem;
max-width: 80ch;
margin: 0 auto;
}
dialog {
padding: 2rem;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
/* 模态打开时由浏览器生成的遮罩层 */
dialog::backdrop {
background-color: rgba(0, 0, 0, 0.5);
}
button {
padding: 0.5rem 1rem;
font-size: 1rem;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Light Dismiss Dialog Demo</h1>
<!-- 第 1、2 条:closedby="any" + 可访问名称 -->
<dialog id="lightDismissDialog" closedby="any" aria-labelledby="dialogTitle">
<h2 id="dialogTitle">Welcome!</h2>
<p>This modal dialog can be closed by clicking outside of its content (on the backdrop) or by pressing the <code>Esc</code> key.</p>
<!-- 第 6 条:表单提交即关闭 -->
<form method="dialog">
<button type="submit">Close</button>
</form>
</dialog>
<button id="openButton" class="test-dialog-trigger">Open Dialog</button>
<script>
const dialog = document.getElementById('lightDismissDialog');
const openButton = document.getElementById('openButton');
// 第 3 条:必须使用 showModal()
openButton.addEventListener('click', () => {
dialog.showModal();
});
// 第 8 条:不支持 closedby 时的降级
if (!('closedBy' in HTMLDialogElement.prototype)) {
dialog.addEventListener('click', (event) => {
if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
const isInDialog = (
rect.top <= event.clientY &&
event.clientY <= rect.top + rect.height &&
rect.left <= event.clientX &&
event.clientX <= rect.left + rect.width
);
if (!isInDialog) {
dialog.close();
}
}
});
}
</script>
</body>
</html>
注意示例中的触发按钮带有 class="test-dialog-trigger"。这不是样式类,而是评分器约定的选择器:grader.ts 通过 .test-dialog-trigger 定位打开按钮。同理,任务描述 tasks/task.md 也把这个类名写进了对 Agent 的自然语言指令中——"触发元素应带有 test-dialog-trigger 类,并且必须在用户点击遮罩任意位置时关闭"。这说明在评测型仓库里,选择器契约是需求的一部分,随手改名会导致无法自动化验证。
遮罩样式的两点说明
guide.md 额外给出了带模糊的遮罩写法:
dialog::backdrop {
background-color: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(2px); /* Optional: add blur for modern browsers */
}
::backdrop只在模态状态(showModal())下由浏览器生成,非模态对话框不会有它,这正是"不要用closedby处理非模态对话框"的视觉层面原因。backdrop-filter被标注为可选。它属于纯装饰增强,缺失时遮罩仍然是半透明纯色,不影响任何一条验收标准。- 总指南还建议给
dialog:modal与dialog::backdrop加overscroll-behavior: contain,防止在遮罩上滚动时把页面背后的内容一起滚走。这属于相邻课题,不影响本文八条,但在真实产品里值得一并处理。
五、反例长什么样,为什么它会挂掉
negative-demo.html 把常见的错误做法集中呈现:
<!-- ERROR: No closedby, no aria, no id that matches labels -->
<dialog id="wrongDialog">
<p>I am a broken dialog.</p>
<!-- ERROR: Button that doesn't close anything -->
<button id="uselessButton">Close (Not really)</button>
</dialog>
openButton.addEventListener('click', (e) => {
e.preventDefault();
// Do absolutely nothing so the dialog never opens
});
// Buggy logic without any valid close() string signature
dialog.addEventListener('click', () => {
dialog.style.display = 'none';
});
对照八条标准,它几乎处处违规:
| 期望 | 反例的违规点 |
|---|---|
1. closedby="any" |
属性完全缺失 |
| 2. 可访问名称 | 没有 aria-label,也没有可指向的标题 ID |
3. showModal() |
触发器被 preventDefault() 阻断且不打开对话框 |
4/5. 遮罩点击与 Esc |
对话框根本打不开,两条都无法满足 |
| 6. 内部关闭按钮 | 按钮没有 type="submit"、不在 method="dialog" 表单内,也不调用 close() |
| 7. 点内容不关闭 | 点击监听无任何内部/外部判断,行为不可控 |
| 8. 降级机制 | 脚本中不存在 getBoundingClientRect 与 .close() 组合 |
尤其值得注意的是最后一段"用 display: none 假装关闭"。这正是 expectations.md 第 8 条要求脚本中出现 .close() 的原因:display: none 只是视觉隐藏,对话框仍处于打开状态、仍在 top layer、焦点与惰性状态都没被正确解除,returnValue、close 事件、焦点回归全部失效。真正的关闭只有 dialog.close() 或 method="dialog" 表单提交。
六、把期望落到测试:grader.ts 的验证策略
grader.ts 通过环境变量 TARGET_FILE 取得被测页面,并用 page.route 把 http://localhost/* 映射到本地文件,因此无需启动真实服务器:
const filePath = path.resolve(targetFile);
const targetDir = path.dirname(filePath);
const demoName = path.basename(filePath);
const demoUrl = `http://localhost/${demoName}`;
await page.route('http://localhost/*', async (route) => {
const requestPath = new URL(route.request().url()).pathname;
const localFilePath = path.join(targetDir, requestPath === '/' ? demoName : requestPath);
if (fs.existsSync(localFilePath)) {
await route.fulfill({ path: localFilePath });
} else {
await route.continue();
}
});
八条期望对应八个 test(),映射关系清晰:
| 测试名 | 验证手段 |
|---|---|
must have the closedby="any" attribute |
expect(dialog).toHaveAttribute('closedby', 'any') |
should have an accessible name |
读取 aria-label / aria-labelledby 并检查目标元素存在 |
must be opened with showModal() |
点击触发器后检查 matches(':modal') |
Clicking the backdrop must close |
page.mouse.click(10, 10) 后断言无 open |
Pressing the Esc key must close |
page.keyboard.press('Escape') 后断言无 open |
Clicking the "Close" button ... must close |
按 `/(Close |
Clicking inside the dialog content should NOT close |
点击 h2, p 后断言仍有 open |
should include a fallback mechanism |
扫描页面脚本文本包含 getBoundingClientRect 与 .close() |
这些断言的写法本身也传递了工程经验:
- 状态检查用属性而不是可见性。
toHaveAttribute('open', '')直接反映对话框的语义状态,比判断 CSSdisplay更可靠。 - 关闭类断言都带
timeout: 2000。关闭可能发生在事件处理的下一帧或过渡动画之后,留出等待窗口能减少偶发失败。 - "不应关闭"用正向断言,即断言
open仍存在,而不是断言"没有发生某事",这样失败信息更明确。
七、容易遗漏的四条实践约束
guide.md 的 Constraints & Accessibility 段落里还有几条不属于八条期望、但会直接影响用户可用性的规则,值得单列:
1. 不要用 click 承载"关闭前必须完成"的逻辑。 因为遮罩点击时事件目标就是 dialog 本身,click 的语义边界模糊;需要在关闭前执行逻辑时,应监听 close 或 cancel 事件。cancel 在 Esc 与 request-close 时触发,此时可以 preventDefault() 阻止关闭(适合"有未保存改动"的场景)。
2. 有未保存改动时应改用 closedby="none" 并给出确认路径。 对话框总指南进一步给出可访问性细节:如果阻止了关闭,必须在界面上可见地说明原因,并通过 aria-describedby 从即将获得焦点的控件引用这条提示,否则屏幕阅读器用户只会听到一个新按钮的名字,完全不知道对话框为什么没关。同时不要让确认操作把按钮移到指针下方,避免连点造成误操作。
3. 不要自己造焦点陷阱。 showModal() 已经让页面其余部分惰性、把焦点限制在对话框内,并在关闭后把焦点归还给触发元素。手写 inert 切换或焦点循环不仅多余,还容易与原生行为打架。
4. Esc 冲突要在组件层解决,而不是全局禁用。 若对话框内含菜单、组合框等同样响应 Esc 的控件,应由这些控件在聚焦时消费按键。
八、与仓库其它指南的关系
这份 expectations.md 并非孤立存在,它是"对话框"这一主题在仓库中的一处切片:
- guides/ui-components/dialog/guide.md 是总纲,负责"该用
<dialog>还是popover""该用哪种关闭策略"这类选型判断,并给出了更严格的降级实现与returnValue复用注意事项。 - guides/ui-behaviors/platform-controls-dismiss-dialog/guide.md 关注"关闭请求"这一侧:
Esc、移动端返回手势、辅助技术的 dismiss 动作。它明确指出模态对话框默认就等于closedby="closerequest",并建议把移动端返回手势的支持当作渐进增强,因为目前没有可靠的 polyfill 手段。 - 本文讨论的 light-dismiss 用例则聚焦"点击遮罩"这一条额外通道,要求把它做成声明式 + 可降级的组合。
仓库中还有一条自动化嗅探规则与该主题呼应:src/analyzing/rules/dialog.ts 会扫描代码中"手写遮罩点击关闭"的模式——即注册 click、判断 event.target === dialog 或 getBoundingClientRect() 坐标、随后调用 .close() 的处理器——并提示改用声明式的 <dialog closedby="any">。规则里的一个细节很能说明"降级代码是正当的":如果文件里存在 'closedBy' in ... 这样的特性检测,规则会直接跳过告警:
if (
(ctx.fileContent.includes('closedBy') || ctx.fileContent.includes('closedby')) &&
/('closedBy'|"closedBy"|'closedby'|"closedby")\s+in\b/i.test(ctx.fileContent)
) {
return [];
}
换言之,仓库对"手写 light-dismiss"的态度是分层的:无条件的旧式监听应当现代化为声明式属性;而带特性检测的降级脚本是规范允许的、甚至是必须的。这与 expectations.md 前七条"用声明式"和第 8 条"必须有降级"的组合完全自洽。
九、上线前自检清单
对照八条期望,逐项确认:
- [ ]
<dialog>上有closedby="any",且该对话框确实以showModal()或command="show-modal"打开。 - [ ] 对话框有
aria-labelledby指向真实存在的标题元素,或使用aria-label;没有多余的role="dialog"/aria-modal。 - [ ] 打开后
dialog.matches(':modal')为true,::backdrop样式生效。 - [ ] 点击遮罩可关闭(可在视口角落点一下验证,注意不要把对话框面板做成铺满全屏)。
- [ ] 按
Esc可关闭;若含菜单、组合框等组件,确认它们聚焦时的Esc不会误关整个对话框。 - [ ] 内部存在可见、可聚焦、有可访问名称的关闭按钮,推荐用
<form method="dialog">+type="submit"。 - [ ] 点击标题、正文、内边距、子元素间空隙均不会关闭。
- [ ] 存在
'closedBy' in HTMLDialogElement.prototype的降级分支,且降级逻辑基于几何坐标而非仅event.target。 - [ ] 关闭一律走
close()或表单提交,绝不使用display: none冒充关闭。 - [ ] 需要拦截关闭时(如未保存改动),改为
closedby="none"并在cancel事件中处理,同时提供可见提示与aria-describedby关联。
这份清单的价值在于它把一句模糊的产品需求——"点外面就该关掉"——变成了可执行、可测试、可跨浏览器降级的三层结构:声明式的 closedby="any" 负责现代浏览器的正确性,showModal() 负责模态语义与焦点管理,closedBy 特性检测负责旧环境下的等效体验。这也正是 modern-web-guidance 这类仓库把 expectations.md 单独抽出来维护的意义:需求、实现与验证三者共用同一份可判定的契约。