Modern Web Guidance:用 Interest Invokers 实现声明式“兴趣触发”操作预览(interest-triggered action previews)
Modern Web Guidance:用 Interest Invokers 实现声明式“兴趣触发”操作预览(interest-triggered action previews)
本文基于 Modern Web Guidance(modern-web-guidance-src)仓库中 interest-triggered-action-previews 指南 及其配套的任务定义、演示与评分脚本,系统讲解如何利用实验性 Web 平台特性 Interest Invokers API,以纯声明式方式在用户“表现出兴趣”(悬停、聚焦或长按)但尚未点击之前,实时预览按钮将要产生的效果。读完后你将掌握:interestfor 属性的声明式关系建立、interest / loseinterest 事件的处理、:interest-source / :interest-target 伪类与 interest-delay 时序控制、条件式 polyfill 安装策略,以及为什么这类预览绝不能通过 live region 播报。
场景:一个真实的落地任务
该指南对应的评测任务定义在 task.md 中,其 frontmatter 指定基准应用为 daily-grind:
---
base_app: daily-grind
---
基准应用是仓库内置的咖啡店站点 daily-grind/index.html,其首页包含一个 “Seasonal Favorites” 区块,以卡片网格展示三款季节饮品(Maple Oat Latte、Dark Roast Espresso、Cold Brew),每张卡片底部都有一个 View Details 链接:
<!-- 来自 src/harness/base-apps/daily-grind/index.html -->
<section>
<h2 style="text-align: center;">Seasonal Favorites</h2>
<div class="grid">
<div class="card">
<h3>Maple Oat Latte</h3>
<p>Creamy oat milk with a hint of Vermont maple syrup.</p>
<a href="/menu/seasonal" class="btn">View Details</a>
</div>
<!-- …Dark Roast Espresso / Cold Brew 卡片… -->
</div>
</section>
任务要求(task.md 以三种不同表述给出,核心语义一致):
- 在首页 “Seasonal Favorites” 区块下方新增一个
id="seasonal-preview"的实时预览框:当用户 hover、聚焦或长按 任一 “View Details” 按钮时,预览该按钮对应饮品(如 “Maple Oat Latte” 或 “Cold Brew”)的信息或强调色;当用户移开或失焦时,重置回占位文案(“Select a drink to preview” / “choose a seasonal drink”); - 明确要求使用声明式 HTML(即平台特性 Interest Invokers)实现,而不是给每个按钮挂 hover / focus 监听器;
- 明确要求该预览不产生任何 live region 播报噪音。
这就是 Interest Invokers 的典型用例:用户在提交操作(点击)之前,以零 JS 事件监听的方式获得“行动前预览”。
核心机制:声明式的兴趣关系
Interest Invokers 是一个实验性的 Web 平台特性,提供声明式方式在“兴趣源”(interest source,即按钮或链接)与“兴趣目标”(interest target)之间建立兴趣关系。关系一旦建立,开发者就能用 CSS 和 JavaScript 对“产生兴趣”与“兴趣消失”作出响应。
1. 用 interestfor 建立关系
在按钮或链接(兴趣源)上设置 interestfor 属性,其取值是兴趣目标的 ID 引用。约束是:一个兴趣源只能指向一个兴趣目标,但一个兴趣目标可以拥有多个兴趣源——这与本任务中多个 View Details 按钮共享同一个 #seasonal-preview 预览框的结构完全吻合:
<!-- MANDATORY: interest relationships must be established with the `interestfor` attribute on a button or a link -->
<button interestfor="interestingElement" data-effect="A">Some effect</button>
<button interestfor="interestingElement" data-effect="B">Some other effect</button>
<div id="interestingElement">Something interesting</div>
对应到 daily-grind 场景,就是在 Seasonal Favorites 的每个 View Details 链接上加上 interestfor="seasonal-preview",并在网格下方放置 <div id="seasonal-preview">Select a drink to preview</div>。
2. 监听目标上的 interest 与 loseinterest 事件
这两个事件都会派发到兴趣目标上,且都是 InterestEvent,带有 source 属性,指向触发兴趣的源元素(即带 interestfor 属性的那个按钮/链接)。因此只需要在预览框上注册两个监听器,无需为每个按钮写任何监听逻辑:
interestingElement.addEventListener("interest", event => {
// Apply the preview based on `event.source`
event.target.dataset.preview = event.source.dataset.effect;
});
interestingElement.addEventListener("loseinterest", event => {
// Unapply the preview
delete event.target.dataset.preview;
});
event.source 是区分“是哪个按钮触发了预览”的关键——多个源共享一个目标时,靠它读取源上携带的数据(如 data-effect、aria-label)。
3. 用伪类选择器描述激活态
处于活跃兴趣状态的兴趣源和目标可以分别用 :interest-source 和 :interest-target 伪类选中,纯 CSS 即可表达“预览中”的视觉状态:
/* Styles to apply when the effect is being previewed */
:interest-source {}
:interest-target {}
4. 用 interest-delay 控制时序
兴趣源(带 interestfor 的元素)的“兴趣建立延迟”与“兴趣解除延迟”可用 interest-delay-start 与 interest-delay-end 两个 CSS 属性设置,或使用简写属性 interest-delay:
[interestfor] {
interest-delay-start: 0.2s;
interest-delay-end: 0.1s;
}
从特性参考文档 interest-invokers.md 的 Timing 一节可知:默认情况下鼠标与键盘用户的兴趣展示/解除都带有半秒延迟。这个默认值是有意的——它防止用户 Tab 遍历页面或鼠标扫过页面时目标频繁开关,也防止鼠标从触发器移向目标时目标提前关闭。若用户会在短时间内连续切换多个触发器,可以在已有兴趣触发器打开时将初始延迟降为 0:
:root:has(:interest-source) [interestfor] {
interest-delay-start: 0s;
}
可访问性红线:不要用 live region 播报预览
指南中有一条以 NOTE 形式强调、且被 expectations 与评分器硬性验收的规则:
不要用 live region 播报兴趣驱动的预览。 Interest 可能只是指针扫过页面或 Tab 经过相邻按钮就会触发,apply/unapply 的播报会迅速变成噪音,淹没用户真正关心的内容。预览本身就是 affordance:能感知它的用户直接受益;不能感知的用户也不会从 “Previewing effect: A” 这样的口头复读中受益。若你确实认为某个具体场景需要播报,务必先与用户仔细测试。
仓库中 expectations.md 将其列为 MUST NOT:
The implementation MUST NOT announce interest-driven preview state changes via a live region (e.g.
role="status"/aria-live). Interest is a passive signal and broadcasting every apply/unapply produces noise; reserve announcements for committed actions (e.g. on click).
原则可以概括为:兴趣是被动的、可忽略的信号,预览内容用户“错过也没关系”;只有已提交的动作(如点击)才值得播报。 仓库中的反例 negative-demo.html 恰好演示了错误做法——它有一个 role="status" aria-live="polite" 的隐藏播报区,并且每次 mouseenter / mouseleave / focus / blur 都往里面写入 Previewing Red、Color Applied 之类的文本,这正是需要被避免的噪音来源。
完整参考实现:demo.html
仓库内 demo.html 是该特性“颜色预览”参考实现,结构与 daily-grind 任务同构(多个 swatch 按钮 → 一个预览框)。其关键片段如下。
HTML 部分:每个颜色按钮只声明 interestfor,数据放在 data-* 上,名称放在 aria-label 上:
<p class="color-grid">
<button interestfor="preview-box" style="background: #ef4444" data-color="#ef4444" aria-label="Red"></button>
<button interestfor="preview-box" style="background: #3b82f6" data-color="#3b82f6" aria-label="Blue"></button>
<button interestfor="preview-box" style="background: #22c55e" data-color="#22c55e" aria-label="Green"></button>
</p>
<div id="preview-box" class="preview-box">Preview Area</div>
CSS 部分同时写了原生伪类与 polyfill 类(见下节):
/* Style the invoker while interest is shown */
.color-grid button:is(:interest-source, .interest-source) {
border-color: #000;
}
/* Style the target while interest is shown */
.preview-box:is(:interest-target, .interest-target) {
border-style: dashed;
border-color: #666;
}
JS 部分展示了两点工程细节:polyfill 条件安装与通过 e.source 读取源数据:
if (!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")) {
await import("https://unpkg.com/interestfor@latest");
}
const previewBox = document.getElementById('preview-box');
let appliedColor = '';
// 注意:这里刻意不向 live region 广播预览状态
previewBox.addEventListener('interest', (e) => {
// e.source is the element that triggered the interest
previewBox.style.backgroundColor = e.source.dataset.color;
previewBox.textContent = `Previewing ${e.source.ariaLabel}`;
});
// 用户停止交互时还原为“已应用”状态或初始占位
previewBox.addEventListener('loseinterest', () => {
previewBox.style.backgroundColor = appliedColor;
previewBox.textContent = appliedColor ? 'Color Applied' : 'Preview Area';
});
loseinterest 中区分“已有已提交颜色”与“从未提交”的处理(还原到 appliedColor 或占位文案),对应任务中“移开时重置回 Select a drink to preview”的要求。
Fallback:条件式安装 interestfor polyfill
指南末尾的 {{ FEATURE_FALLBACKS("interest-invokers") }} 宏会展开特性参考文档 interest-invokers.md 的 Fallbacks 章节(宏的展开逻辑见 macros.ts 中的 FEATURE_FALLBACKS 实现)。其规则是:
- 必须使用 NPM 上的
interestforpolyfill 包做条件式安装,优先打包(bundling)而非 CDN; - MANDATORY:通过检测
HTMLButtonElement.prototype上的interestForElement属性做特性检测,仅在缺少原生支持时加载 polyfill:
<script type="module">
if (!("interestForElement" in HTMLButtonElement.prototype)) {
// CDN link only used for example, prefer bundling.
await import("https://unpkg.com/interestfor@latest");
}
</script>
仓库 demo 采用了更严格的 hasOwnProperty 变体,两者表达同一意图:原生支持的浏览器绝不加载 polyfill。这一要求被评分器 grader.ts 双向验证:先人为给 HTMLButtonElement.prototype 注入 interestForElement(模拟原生支持),断言页面不会发出任何 interestfor polyfill 请求;再在新页面中 delete 掉各原型上的该属性(模拟不支持),断言页面会加载 polyfill。
CSS polyfill 的两个坑
在 polyfill 路径下,由于浏览器不认识原生伪类与属性,CSS API 有细微变化:
- 伪类:polyfill 无法定义真正的
:interest-source/:interest-target,而是给元素加.interest-source/.interest-target类。MANDATORY:用:is()将两者合并书写,以同时覆盖原生与 polyfill 两种状态:
:is(:interest-source, .interest-source) { /* ... */ }
:is(:interest-target, .interest-target) { /* ... */ }
- 延迟属性:polyfill 无法在所有浏览器中直接读取这些自定义属性,要求通过 CSS 自定义属性(CSS 变量)中转:
[interestfor] {
--interest-delay-start: 0.2s;
interest-delay-start: var(--interest-delay-start);
--interest-delay-end: 0.1s;
interest-delay-end: var(--interest-delay-end);
}
这正是 demo.html 中按钮样式采用 --interest-delay-start: 300ms; interest-delay-start: var(--interest-delay-start); 写法的原因——同一份 CSS 在原生与 polyfill 环境下都生效。
另外,interest-invokers.md 的可访问性章节还给出两条与预览实现相关的硬性约束:不要在选择器已具备 aria-label / 可见文本时重复播报名称;不要在兴趣展示时移动焦点(不要 autofocus、不要在 interest 监听器里调用 focus()),否则违反 WCAG 3.2.1(On Focus)。
验证标准:expectations 与 Playwright grader
该指南目录下的 expectations.md 给出了五条验收清单,grader.ts 则将其逐条实现为 Playwright 测试(基于仓库的 test-fixture.ts 公共夹具):
| 验收点 | grader 验证方式 |
|---|---|
源元素(按钮)必须带指向目标 ID 的 interestfor 属性 |
选取第一个 [interestfor] 元素,断言其属性值非空,且 #<targetId> 目标存在于 DOM 中 |
目标必须响应 interest 事件展示预览态 |
读取目标的初始文本与背景色,向目标派发带 source 属性的 interest 事件,断言文本或背景色发生了变化 |
目标必须响应 loseinterest 事件还原预览态 |
先派发 interest 再派发 loseinterest,断言最终文本与背景色与初始值一致(测试前注入 * { transition: none !important; } 以排除过渡动画干扰) |
| polyfill 必须条件式安装 | 如上文所述:注入 interestForElement 时断言无 polyfill 请求;删除该属性时断言发出 polyfill 请求 |
| 不得用 live region 播报预览状态变化 | 采集页面所有 [aria-live], [role="status"], [role="log"], [role="alert"], [role="marquee"], [role="timer"] 的初始文本,然后依次 hover、focus、blur 前两个触发器,用 expectNever 断言 800ms 内这些区域的文本始终未变 |
最后一条测试还透露了一个时序细节(grader 源码注释):interest 事件在 interest-delay-start(默认 0.5s)之后才触发,因此观察窗口必须长于该延迟(800ms)才能覆盖真实行为。
小结:正向与负向实现的差异
把 demo.html 与 negative-demo.html 对照,可以得到一张清晰的“做与不做”清单:
- 正向:
interestfor声明式关系 + 目标上的interest/loseinterest两个监听器 +:is(:interest-source, .interest-source)等合并选择器 +interestForElement特性检测下的条件 polyfill + 无 live region 参与; - 负向:给每个按钮挂
mouseenter/mouseleave/focus/blur四组监听器 + 无条件引入 polyfill + 每个按钮都带role="status"播报文本。
对于 daily-grind 这个基准应用,正确实现即:为 Seasonal Favorites 下的每个 View Details 链接添加 interestfor="seasonal-preview",在网格下方添加 <div id="seasonal-preview">Select a drink to preview</div>,在该目标上监听 interest / loseinterest(依据 event.source 切换饮品预览与占位文案),必要时以 interest-delay 调整时序,条件式安装 interestfor polyfill,并让点击这类“已提交动作”承担所有需要播报的语义。该指南与配套资产均位于 interest-triggered-action-previews 目录,可结合 interest-triggered-tooltips 等同一 API 的其他用例进一步学习 Interest Invokers 的边界与配套 ARIA 策略。