tabindex-no-positive

Try in Playground
jsx-a11y

oscar143

Best PracticeInformational

0

No tags

No CWE or CVE

jsx-a11y/tabindex-no-positive

Avoid positive tabIndex property values to synchronize the flow of the page with keyboard tab order.

Accessibility guidelines

  • WCAG 2.4.3

Resources

Ast Rule: html element


tabindex-no-positive

How to write a rule
const TYPES = {
  string: getPropStringValue,
  sequence: getPropSequenceValue,
  array: getPropArrayValue,
  object: getPropObjectValue,
  object_element: getPropObjectValue,
  functiondefinition: () => {},
};

function getProp(attributes = [], prop = "") {
  if (!prop) return;

  return attributes.find((attribute) => {
    if (attribute && attribute.name && attribute.name.value) {
      return attribute.name.value === prop;
    }
  });
}

function getPropStringValue(value) {
  if (value.value === "true") {
    return true;
  }

  if (value.value === "false") {
    return false;
  }

  return value.value.replace(/^\"/g, "").replace(/\"$/g, "");
}

function getPropArrayValue(value) {
  const array = [];
  const arrayElements = value.elements;

  if (arrayElements.length) {
    for (const element of arrayElements) {
      array.push(TYPES[element.astType](element));
    }
  }

  return array;
}

function getPropObjectValue(value) {
  const object = {};
  const objectElements = value.elements;

  if (objectElements.length) {
    for (const element of objectElements) {
      object[element.name.value] = TYPES[element.value.astType](element.value);
    }
  }

  return object;
}

function getPropSequenceValue(value) {
  if (value.elements.length) {
    const element = value.elements[0];

    if (element) {
      return TYPES[element.astType](element);
    }
  }
}

function extractValue(attribute, extractor) {
  if (attribute) {
    // Null valued attributes imply truthiness.
    // For example: <div aria-hidden />
    if (attribute.value === null) return true;

    return extractor(attribute.value);
  }
}

function getValue(value) {
  return TYPES[value.astType](value);
}

function getPropValue(attribute) {
  return extractValue(attribute, getValue);
}

function visit(node, filename, code) {
  const tabIndex = Number(getPropValue(getProp(node.attributes, "tabindex")));


  if (isNaN(tabIndex) || tabIndex <= 0) return;

  const error = buildError(
    node.start.line,
    node.start.col,
    node.end.line,
    node.end.col,
    "Enforce `tabIndex` value is not greater than zero.",
    "INFO",
    "BEST_PRACTICES"
  );

  addError(error);
}

good.jsx

Expected test result: no error

<div tabindex="-1" />

bad.jsx

Expected test result: has error

tab index greater than 0

<div tabindex="2" />
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.