如何强制所有动画时长超过 1s 的代码块提供媒体查询关闭选项?

解读

面试官想确认两件事:

  1. 你能否用 Stylelint 的“规则+插件”体系把“动画时长>1s”这一运行时特征转换成静态可分析的语法模式;
  2. 你能否把“必须提供关闭选项”这一业务约束落地为可校验、可自动修复的代码规范。
    国内大厂目前普遍把“可访问性”与“性能”纳入 CI 门禁,动画时长正是 Lighthouse 扣分项,因此这道题既考技术深度,也考你对国内合规要求的理解。

知识点

  1. Stylelint 规则执行模型:
    • 每条规则都是一个接收 Root 与 PostCSS API 的函数,通过 walkAtRules/walkDecls 遍历节点。
    • 规则可同步或异步返回 report(),并可通过 context.fix 提供自动修复。
  2. 时长提取与换算:
    • 动画总时长 = animation-duration × animation-iteration-count(缺省为 1)。
    • 需统一换算成毫秒做比较,注意 s/ms 单位及小数。
  3. 关闭选项的静态表征:
    • 国内团队约定俗成的写法是“在代码块尾部紧跟一个媒体查询,其中包含 prefers-reduced-motion: reduce 并把对应动画置为 none”。
    • 因此规则只需校验“同一作用域内(同一文件或同一父选择器)是否存在满足条件的媒体查询”,不必真正运行浏览器。
  4. 插件包结构:
    • 必须提供 index.js(导出一个规则数组)与 rules/ 目录,并在 package.json 中声明 stylelint-plugin 关键字,才能被 extends 引用。
  5. 自动修复策略:
    • 若缺失媒体查询,可在原规则后插入 /* stylelint-disable-next-line */ 注释并追加媒体查询节点,保证修复后无语法错误。
  6. 性能与误报:
    • 使用 Once 钩子而非 Root 钩子,避免重复遍历;
    • 对 var() 或 calc() 等无法静态求值的声明,直接放过并给出提示,防止误杀。

答案

  1. 创建插件目录

    stylelint-plugin-animation-a11y/
    ├── index.js
    └── rules/
        └── require-reduced-motion.js
    
  2. 主入口 index.js

    module.exports = [require('./rules/require-reduced-motion')];
    
  3. 规则实现 require-reduced-motion.js

    const { utils } = require('stylelint');
    const ruleName = 'plugin/require-reduced-motion';
    const messages = utils.ruleMessages(ruleName, {
      expected: (selector) =>
        `动画时长超过 1s,必须在同一作用域内提供 prefers-reduced-motion 关闭选项 (${selector})`,
    });
    
    const DURATION_LIMIT = 1000; // ms
    
    function ms(value) {
      const num = parseFloat(value, 10);
      return value.includes('ms') ? num : num * 1000;
    }
    
    module.exports = utils.createPlugin(ruleName, (primaryOption, secondaryOption, context) => {
      return (root, result) => {
        const validOptions = utils.validateOptions(result, ruleName, {
          actual: primaryOption,
          possible: [true, false],
        });
        if (!validOptions || !primaryOption) return;
    
        const animations = new Map(); // key: selector, value: { node, duration }
    
        // 第一步:收集动画声明
        root.walkDecls('animation', (decl) => {
          const value = decl.value;
          const durationMatch = value.match(/^([\d.]+m?s)/);
          if (!durationMatch) return;
          const duration = ms(durationMatch[1]);
          const iterationMatch = value.match(/([\d.]+)\s*$/);
          const iterations = iterationMatch ? parseFloat(iterationMatch[1], 10) : 1;
          const total = duration * iterations;
          if (total > DURATION_LIMIT) {
            const selector = decl.parent.selector;
            animations.set(selector, { node: decl, duration: total });
          }
        });
    
        // 第二步:收集已有关闭选项
        const hasMediaQuery = new Set();
        root.walkAtRules('media', (atRule) => {
          if (atRule.params.includes('prefers-reduced-motion: reduce')) {
            atRule.walkDecls('animation', (decl) => {
              if (decl.value === 'none') {
                hasMediaQuery.add(decl.parent.selector);
              }
            });
          }
        });
    
        // 第三步:对比并报告
        animations.forEach(({ node, duration }, selector) => {
          if (hasMediaQuery.has(selector)) return;
          utils.report({
            message: messages.expected(selector),
            node,
            result,
            ruleName,
            fix(fixer) {
              if (context.fix) {
                const mediaNode = node.parent.cloneAfter();
                mediaNode.selector = `${selector}`;
                mediaNode.append('animation: none;');
                const media = node.parent.parent;
                const newMedia = media.cloneAfter({
                  params: '(prefers-reduced-motion: reduce)',
                });
                newMedia.append(mediaNode);
              }
            },
          });
        });
      };
    });
    
  4. 使用方式
    在项目 .stylelintrc.js 中:

    module.exports = {
      plugins: ['./stylelint-plugin-animation-a11y'],
      rules: {
        'plugin/require-reduced-motion': true,
      },
    };
    
  5. 验证

    .fadeIn {
      animation: fadeIn 1.2s ease;
    }
    

    运行 npx stylelint src/**/*.css 会报错并自动修复为:

    .fadeIn {
      animation: fadeIn 1.2s ease;
    }
    @media (prefers-reduced-motion: reduce) {
      .fadeIn {
        animation: none;
      }
    }
    

拓展思考

  1. 多动画简写:
    若 animation 同时声明多个动画,需拆分每个动画名称与对应时长,再分别计算总时长。
  2. 变量与混合:
    在 SCSS/Less 中,时长可能是 $duration 或 @duration,可通过 postcss-scss 的 variable 节点做二次求值,若无法静态解析则降级为警告而非错误。
  3. 作用域精度:
    同一选择器可能分散在多个文件,可借助 Stylelint 的 configBasedir 与 globby 做跨文件聚合,或在设计规范里强制“一个组件一个文件”,降低实现复杂度。
  4. 国内合规场景:
    工信部《APP 用户权益保护测评规范》已把“不可关闭动画”列为感知性能缺陷,因此该规则可直接接入 GitHub Actions 或 GitLab CI,作为 MR 的必过门禁,并同步输出报告给法务/质检部门。