写一个 play 函数遍历所有可聚焦元素并记录 tab 顺序
解读
在国内前端面试中,Storybook 的 play 函数常被用来验证组件的可访问性(a11y)与交互一致性。
题目表面是“遍历可聚焦元素”,实质考察三点:
- 是否知道 play 函数的执行时机(Storybook 在画布渲染完成后自动调用)。
- 能否用 DOM 标准 而非“肉眼找元素”筛选可聚焦节点(避免漏掉
contenteditable、tabindex="0"等场景)。 - 是否理解 tab 顺序 由
tabindex值与 DOM 位置共同决定,并会按浏览器真实规则排序,而不是简单querySelectorAll顺序。
如果候选人只写 document.querySelectorAll('button, input...'),会被追问“那 summary、contenteditable、shadow DOM 怎么办?”;如果直接 element.tabIndex 取值排序,会被追问“正数 tabindex 优先级高于正常流,怎么排?”——必须给出与浏览器行为一致的算法。
知识点
-
play 函数签名
play: async ({ canvasElement }) => { ... }
canvasElement是 Storybook 隔离渲染的根节点,必须限定遍历范围,防止污染侧边栏或插件区域。 -
可聚焦元素的判定标准
- 内置可聚焦标签:
button, a[href], input, select, textarea, details>summary:first-of-type, iframe, object, embed, audio[controls], video[controls] - 显式
tabindex值:-1仅脚本聚焦,0与正整数参与 tab 顺序 - Shadow DOM 内元素 需递归
shadowRoot - 禁用(disabled)元素 不可聚焦,需过滤
- display:none / visibility:hidden / hidden 元素不可聚焦
- 内置可聚焦标签:
-
tab 顺序算法
浏览器分两步:
a. 收集所有tabindex >= 0的元素
b. 先按tabindex正数升序,再按 DOM 位置(document order)
正数tabindex一旦使用,就会打断自然流,必须单独排序后再拼接tabindex=0组。 -
Storybook 测试友好
- 用
userEvent.tab()逐一触发,可验证视觉焦点环与顺序是否一致 - 把结果写成 JSON 快照 或 console.table,方便 CI 回归
- 若组件库需满足中国国标 GB/T 37668-2019(信息无障碍),顺序必须与**视觉阅读顺序(左→右,上→下)**一致,否则视为缺陷
- 用
答案
// Button.stories.ts(以 React 为例,Vue 同理)
import type { Meta, StoryObj } from '@storybook/react';
import { userEvent, within } from '@storybook/testing-library';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
title: 'Example/Button',
component: Button,
};
export default meta;
export const TabOrder: StoryObj = {
args: { children: 'Save' },
play: async ({ canvasElement }) => {
// 1. 限定范围,防止污染 Storybook 外壳
const canvas = within(canvasElement);
// 2. 判定函数:标准聚焦 + 自定义正值 tabindex
const isFocusable = (el: Element): boolean => {
if (el.closest('[inert], [hidden], [aria-hidden="true"]')) return false;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') return false;
if ((el as HTMLElement).disabled) return false;
const tag = el.tagName.toLowerCase();
const hasTabindex = el.hasAttribute('tabindex');
const tabindex = hasTabindex ? Number(el.getAttribute('tabindex')) : null;
// 内置可聚焦标签
const nativelyFocusable =
['button', 'input', 'select', 'textarea', 'a', 'audio', 'video', 'iframe', 'object', 'embed'].includes(tag) ||
(tag === 'summary' && el.parentElement?.tagName.toLowerCase() === 'details');
if (nativelyFocusable && !hasTabindex) return true;
if (tabindex !== null && tabindex >= 0) return true;
if (el.getAttribute('contenteditable') === 'true') return true;
return false;
};
// 3. 递归收集 Shadow DOM
const walk = (root: Element | ShadowRoot, acc: Element[] = []): Element[] => {
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
(node) => (isFocusable(node as Element) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
);
let el;
while ((el = walker.nextNode() as Element)) {
acc.push(el);
if (el.shadowRoot) walk(el.shadowRoot, acc);
}
return acc;
};
const focusableElements = walk(canvasElement);
// 4. 按浏览器规则排序
const sorted = focusableElements.sort((a, b) => {
const getTabindex = (el: Element) => Number(el.getAttribute('tabindex') || 0);
const ta = getTabindex(a);
const tb = getTabindex(b);
// 正数 tabindex 优先,其余按 DOM 顺序
if (ta > 0 && tb > 0) return ta - tb;
if (ta > 0) return -1;
if (tb > 0) return 1;
return 0; // 保持原 DOM 顺序
});
// 5. 记录并打印
const report = sorted.map((el, idx) => ({
index: idx,
tag: el.tagName.toLowerCase(),
text: (el as HTMLElement).innerText?.slice(0, 20) || '',
tabindex: el.getAttribute('tabindex') || '0',
}));
console.table(report);
// 6. 可选:用 userEvent 真实走一遍,验证无报错
for (const el of sorted) {
await userEvent.tab();
if (document.activeElement !== el) {
throw new Error(`Tab 顺序不一致:期望 ${el}, 实际 ${document.activeElement}`);
}
}
},
};
该实现完全对齐浏览器行为,可一键用于 CI 快照比对,满足国内金融、政务等强 a11y 场景。
拓展思考
- 动态场景:若组件内部用
useEffect延迟插入按钮,可在play里先waitFor(() => screen.getByRole('button', { name: '新增' }))再重新收集,保证顺序快照始终最新。 - 跨 iframe 场景:Storybook 的
canvasElement默认不包含iframe内文档,需canvasElement.querySelector('iframe')?.contentDocument递归,注意 CORS 限制。 - 移动端无键盘:国内小程序、App 内嵌 H5 常使用外接扫码枪(模拟 Tab 键),顺序错误会导致扫码后焦点乱跳;可把上述逻辑封装为 Storybook 插件,在所有 stories 上自动跑一次,生成 a11y 报告供测试小姐姐每日回归。
- 性能优化:组件库几百个 stories 时,完整遍历会成为瓶颈;可给
play加开关参数,仅在 MR 阶段跑全量,日常只跑变更组件的依赖树。