|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +"use strict"; |
| 5 | + |
| 6 | +const { hasNonEmptyProp } = require("../util/hasNonEmptyProp"); |
| 7 | +var elementType = require("jsx-ast-utils").elementType; |
| 8 | +const { hasAssociatedLabelViaAriaLabelledBy } = require("../util/labelUtils"); |
| 9 | +const { hasTextContentChild } = require("../util/hasTextContentChild"); |
| 10 | +const { hasToolTipParent } = require("../util/hasTooltipParent"); |
| 11 | + |
| 12 | +//------------------------------------------------------------------------------ |
| 13 | +// Rule Definition |
| 14 | +//------------------------------------------------------------------------------ |
| 15 | + |
| 16 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 17 | +module.exports = { |
| 18 | + meta: { |
| 19 | + // possible error messages for the rule |
| 20 | + messages: { |
| 21 | + noUnlabelledMenuItem: "Accessibility: MenuItem must have an accessible label" |
| 22 | + }, |
| 23 | + // "problem" means the rule is identifying code that either will cause an error or may cause a confusing behavior: https://eslint.org/docs/latest/developer-guide/working-with-rules |
| 24 | + type: "problem", |
| 25 | + docs: { |
| 26 | + description: "Accessibility: MenuItem without label must have an accessible and visual label: aria-labelledby", |
| 27 | + recommended: true, |
| 28 | + url: "https://www.w3.org/TR/html-aria/" // URL to the documentation page for this rule |
| 29 | + }, |
| 30 | + fixable: null, // Or `code` or `whitespace` |
| 31 | + schema: [] // Add a schema if the rule has options |
| 32 | + }, |
| 33 | + |
| 34 | + create(context) { |
| 35 | + return { |
| 36 | + // visitor functions for different types of nodes |
| 37 | + JSXElement(node) { |
| 38 | + const openingElement = node.openingElement; |
| 39 | + // if it is not a MenuItem, return |
| 40 | + if (elementType(openingElement) !== "MenuItem") { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + // if the MenuItem has a text, label or an associated label, return |
| 45 | + if ( |
| 46 | + hasNonEmptyProp(openingElement.attributes, "aria-label") || //aria-label, not recommended but will work for screen reader users |
| 47 | + hasAssociatedLabelViaAriaLabelledBy(openingElement, context) || // aria-labelledby |
| 48 | + hasTextContentChild(node) || // has text content |
| 49 | + hasToolTipParent(context) // has tooltip parent, not recommended but will work for screen reader users |
| 50 | + ) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + // if it has no visual labelling, report error |
| 55 | + context.report({ |
| 56 | + node, |
| 57 | + messageId: `noUnlabelledMenuItem` |
| 58 | + }); |
| 59 | + } |
| 60 | + }; |
| 61 | + } |
| 62 | +}; |
| 63 | + |
0 commit comments