代码之家  ›  专栏  ›  技术社区  ›  Takeshi Tokugawa YD

如何获取“pa11y”中的目标行号和列范围?

  •  0
  • Takeshi Tokugawa YD  · 技术社区  · 2 年前

    根据TypeScript打字 pa11y 退货:

    interface ResultIssue {
        code: string;
        context: string;
        message: string;
        selector: string;
        type: string;
        typeCode: number;
    }
    

    示例值(看起来行TypeScript的打字有点不完整,但 runner runnerExtras 目前看来并不重要):

    {
      code: 'WCAG2AAA.Principle4.Guideline4_1.4_1_2.H91.A.EmptyNoId',
      type: 'error',
      typeCode: 1,
      message: 'Anchor element found with no link content and no name and/or ID attribute.',
      context: '<a><span></span></a>',
      selector: 'html > body > main > a:nth-child(3)',
      runner: 'htmlcs',
      runnerExtras: {}
    }
    

    我想创建类似于下面的输出(下面的输出用于HTML验证,现在的输出用于可访问性检查):

    enter image description here

    然而 第11页 没有为检索的行号和列范围提供API。 那么,我们能做些什么呢? 我对引入源HTML代码没有任何问题,只剩下在HTML代码中检测已发布的片段。

    第一条线索是 context 。也许我们可以使用正则表达式,或者 String.prototype.indexOf() 但如果出现多次呢?如果它总是第一个,我就不好了。

    下一条线索是选择器 html > body > main > a:nth-child(3) 。看起来很独特。使用 node-html-parser ,我们可以通过选择器访问元素,但如何获取行号和列范围?

    0 回复  |  直到 2 年前
        1
  •  1
  •   Fraser    1 年前

    您可以通过解析源HTML,然后使用querySelector访问元素来完成此操作。

    这是假设源HTML包含正确的换行符和换行符(在本例中 \n ). 此外,当您使用pars pre 选项

    然后可以使用的组合 indexOf substring 以查找源HTML中元素的行号。

    例如(此处键入的道歉可能是错误!)

    const { parse } = require('node-html-parser');
    
    // where htmlContent is the source HTML
    const root = parse(htmlContent, {
       pre: true
    });
    
    // where resultIssue.selector is a string such as 'html > body > main > a:nth-child(3)'
    const element = root.querySelector(resultIssue.selector);
    
    if (element) {
      // get the element as HTML string
      const sourceHtml = element.toString();
    
      // find the element in the source html
      const startIndex = htmlContent.indexOf(sourceHtml);
    
      // count the lines (NB: could be `\r\n`)
      const lineNumber = htmlContent.substring(0, startIndex).split('\n').length;
      console.log('Line number:', lineNumber);
    } else {
      console.log('Element not found.');
    }
    

    通过在HTML行字符串中查找元素字符串的索引位置,可以以类似的方式访问近似列位置。