Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
ff35fa6
fix(template-require-mandatory-role-attributes): use axobject-query f…
johanrd Apr 21, 2026
63c7097
docs(template-require-mandatory-role-attributes): cite HTML-AAM as pr…
johanrd Apr 22, 2026
bd3beb5
docs+comment: update stale audit comment + note isSemanticRoleElement…
johanrd Apr 22, 2026
48ef43c
docs: correct audit-fixture CI-run claim (Copilot review)
johanrd Apr 22, 2026
6deae20
docs: address Copilot review wording (PR #51)
johanrd Apr 23, 2026
4cd0bfc
docs(template-require-mandatory-role-attributes): document strict-mod…
johanrd Apr 24, 2026
175ef77
perf(template-require-mandatory-role-attributes): pre-index elementAX…
johanrd Apr 24, 2026
5addb56
chore: remove benchmark scratch file accidentally committed in prior …
johanrd Apr 24, 2026
c85b421
fix(template-require-mandatory-role-attributes): lowercase role; spli…
johanrd Apr 21, 2026
0603f8a
chore: drop temporal 'previously-unflagged' comment
johanrd Apr 21, 2026
d3d5abc
test(audit): align role-has-required-aria fixture with post-rebase be…
johanrd Apr 24, 2026
be757a1
lint: add braces to one-line if per curly rule
johanrd Apr 24, 2026
00d9bb7
fix(#54): address round-2 Copilot review (lowercase tag for case-inse…
johanrd Apr 24, 2026
935ef6f
docs(template-require-mandatory-role-attributes): fix spinbutton requ…
johanrd Apr 24, 2026
0fdf4d4
chore(template-require-mandatory-role-attributes): prettier-align doc…
johanrd Apr 24, 2026
55a1a6c
fix(template-require-mandatory-role-attributes): skip {{input}} seman…
johanrd Apr 24, 2026
4f7f10f
lint: order filename before code in test cases
johanrd Apr 24, 2026
499ec42
test(template-require-mandatory-role-attributes): absorb audit-fixtur…
johanrd Apr 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion docs/rules/template-require-mandatory-role-attributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,39 @@ This rule **allows** the following:
<div role="option" aria-selected="false" />
<CustomComponent role="checkbox" aria-required="true" aria-checked="false" />
{{some-component role="heading" aria-level="2"}}

{{! Native inputs supply required ARIA state for matching roles. Lookup is
based on axobject-query's elementAXObjects + AXObjectRoles (see below). }}
<input type="checkbox" role="switch" />
<input type="checkbox" role="checkbox" />
<input type="radio" role="radio" />
<input type="range" role="slider" />
</template>
```

## Semantic-role exemptions

When the role attribute explicitly declares a role that the native element already provides, the native element supplies the required ARIA state and the rule does not flag missing attributes. The exemption is looked up via [axobject-query](https://github.com/A11yance/axobject-query)'s `elementAXObjects` + `AXObjectRoles` maps, matching the approach used by `eslint-plugin-jsx-a11y` and `@angular-eslint/template`.

Exempt pairings include (non-exhaustive):

| Element | Role | Required ARIA state supplied by |
| ------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------- |
| `<input type="checkbox">` | `checkbox`, `switch` | native `checked` state |
| `<input type="radio">` | `radio` | native `checked` state |
| `<input type="range">` | `slider` | native `value` / `min` / `max` |
| `<input type="number">` | `spinbutton` | native `value` / `min` / `max` (spinbutton's required `aria-valuenow` is derived from the native `value`) |
| `<input type="text">` | `textbox` | no required ARIA |
| `<input type="search">` | `searchbox` | no required ARIA |

Undocumented pairings (e.g. `<input type="checkbox" role="menuitemcheckbox">` — axobject-query does not list this) remain flagged.

## References

- [WAI-ARIA Roles - Accessibility \_ MDN](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles)
- [WAI-ARIA Roles](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles)
- [WAI-ARIA APG — Switch pattern](https://www.w3.org/WAI/ARIA/apg/patterns/switch/)
- [HTML-AAM — `<input type="checkbox">` → `checkbox` role mapping](https://www.w3.org/TR/html-aam-1.1/#el-input-checkbox)
— primary-spec source: the native element's accessibility mapping supplies
the required ARIA state via the `checked` IDL attribute, which is what
axobject-query encodes.
- [axobject-query](https://github.com/A11yance/axobject-query) — AX-tree data source for the exemption lookup (secondary, encodes HTML-AAM)
202 changes: 172 additions & 30 deletions lib/rules/template-require-mandatory-role-attributes.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,188 @@
const { roles } = require('aria-query');
const { AXObjectRoles, elementAXObjects } = require('axobject-query');

function createRequiredAttributeErrorMessage(attrs, role) {
if (attrs.length < 2) {
return `The attribute ${attrs[0]} is required by the role ${role}`;
}

return `The attributes ${attrs.join(', ')} are required by the role ${role}`;
}

function getStaticRoleFromElement(node) {
// ARIA role values are whitespace-separated tokens compared ASCII-case-insensitively.
// Returns the list of normalised tokens, or undefined when the attribute is
// missing or dynamic.
function getStaticRolesFromElement(node) {
const roleAttr = node.attributes?.find((attr) => attr.name === 'role');

if (roleAttr?.value?.type === 'GlimmerTextNode') {
return roleAttr.value.chars || undefined;
return splitRoleTokens(roleAttr.value.chars);
}

return undefined;
}

function getStaticRoleFromMustache(node) {
function getStaticRolesFromMustache(node) {
const rolePair = node.hash?.pairs?.find((pair) => pair.key === 'role');

if (rolePair?.value?.type === 'GlimmerStringLiteral') {
return rolePair.value.value;
return splitRoleTokens(rolePair.value.value);
}

return undefined;
}

function splitRoleTokens(value) {
if (!value) {
return undefined;
}
const tokens = value.trim().toLowerCase().split(/\s+/u).filter(Boolean);
return tokens.length > 0 ? tokens : undefined;
}

// Reads the static lowercase value of `name` from either a GlimmerElementNode
// (angle-bracket attributes) or a GlimmerMustacheStatement (hash pairs).
// Returns undefined for dynamic values or missing attributes.
function getStaticAttrValue(node, name) {
if (node?.type === 'GlimmerElementNode') {
const attr = node.attributes?.find((a) => a.name === name);
if (attr?.value?.type === 'GlimmerTextNode') {
return attr.value.chars?.toLowerCase();
}
return undefined;
}
if (node?.type === 'GlimmerMustacheStatement') {
const pair = node.hash?.pairs?.find((p) => p.key === name);
if (pair?.value?.type === 'GlimmerStringLiteral') {
return pair.value.value?.toLowerCase();
}
return undefined;
}
return undefined;
}

function getMissingRequiredAttributes(role, foundAriaAttributes) {
const roleDefinition = roles.get(role);
// In classic Handlebars (.hbs) `{{input}}` globally resolves to Ember's
// built-in input helper, which renders a native <input>. In strict-mode
// GJS/GTS there is no corresponding lowercase `input` export from
// `@ember/component` (only the PascalCase `<Input>` component), so
// `{{input}}` in strict mode is always a user-bound identifier and cannot
// be assumed to render a native <input>. Treating it as native there
// would silently skip required-ARIA checks on arbitrary components.
function isClassicHbsFilename(context) {
const filename = context.filename || context.getFilename?.() || '';
return !filename.endsWith('.gjs') && !filename.endsWith('.gts');
}

if (!roleDefinition) {
function getTagName(node, context) {
if (node?.type === 'GlimmerElementNode') {
// HTML tag names are case-insensitive; normalize so <INPUT>/<Input> match
// the lowercase keys in AX_CONCEPTS_BY_TAG and the semantic-role maps.
return node.tag?.toLowerCase();
}
if (node?.type === 'GlimmerMustacheStatement' && node.path?.original === 'input') {
if (!context || isClassicHbsFilename(context)) {
return 'input';
}
// Strict-mode {{input}} — not the classic helper, can't claim native.
return null;
}
Comment thread
johanrd marked this conversation as resolved.
Comment thread
johanrd marked this conversation as resolved.
return null;
}

const requiredAttributes = Object.keys(roleDefinition.requiredProps);
const missingRequiredAttributes = requiredAttributes.filter(
(requiredAttribute) => !foundAriaAttributes.includes(requiredAttribute)
);
// Does this {element, role} pair match one of axobject-query's elementAXObjects
// concepts? If so, the native element exposes the role's required ARIA state
// automatically (e.g., <input type=checkbox> exposes aria-checked via the
// `checked` attribute for both role=checkbox and role=switch).
//
// Mirrors jsx-a11y's `isSemanticRoleElement` util
// (https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/src/util/isSemanticRoleElement.js).
//
// Pre-indexed at module load: elementAXObjects is static data, so we resolve
// each concept's exposed-role set once (walking axObjectNames → AXObjectRoles
// → role names) and bucket concepts by tag. That turns the per-call hot path
// into O(concepts-for-this-tag × attrs-on-that-concept), which in practice
// is a handful of entries. Benchmarked at ~12.5× faster than the naive full-
// map walk on a realistic 200k-call workload.
const AX_CONCEPTS_BY_TAG = buildAxConceptsByTag();

return missingRequiredAttributes.length > 0 ? missingRequiredAttributes : null;
function buildAxConceptsByTag() {
const index = new Map();
for (const [concept, axObjectNames] of elementAXObjects) {
const conceptRoles = new Set();
for (const axName of axObjectNames) {
const axRoles = AXObjectRoles.get(axName);
if (!axRoles) {
continue;
}
for (const axRole of axRoles) {
conceptRoles.add(axRole.name);
}
}
const entry = { attributes: concept.attributes || [], roles: conceptRoles };
if (!index.has(concept.name)) {
index.set(concept.name, []);
}
index.get(concept.name).push(entry);
}
return index;
}

function isSemanticRoleElement(node, role, context) {
const tag = getTagName(node, context);
if (!tag || typeof role !== 'string') {
return false;
}
const entries = AX_CONCEPTS_BY_TAG.get(tag);
if (!entries) {
return false;
}
const targetRole = role.toLowerCase();
for (const { attributes, roles: conceptRoles } of entries) {
if (!conceptRoles.has(targetRole)) {
continue;
}
const allMatch = attributes.every((cAttr) => {
const nodeVal = getStaticAttrValue(node, cAttr.name);
if (nodeVal === undefined) {
return false;
}
if (cAttr.value === undefined) {
return true;
}
return nodeVal === String(cAttr.value).toLowerCase();
});
if (allMatch) {
return true;
}
}
return false;
}

// For an ARIA role-fallback list like "combobox listbox", check required
// attributes against the FIRST recognised role (the primary) per ARIA 1.2
// role-fallback semantics — a user agent picks the first role it recognises.
// Abstract roles (widget, input, command, section, … — ARIA §5.3) are
// ontology categories, not valid authoring roles, so UAs skip them too.
//
// When the primary role is a semantic-role element (axobject-query says the
// native element provides the required ARIA state natively — e.g. <input
// type=checkbox role=switch>), the element is exempt: return { role, missing: null }.
//
// Diverges from jsx-a11y, which validates every recognised token.
function getMissingRequiredAttributes(roleTokens, foundAriaAttributes, node, context) {
for (const role of roleTokens) {
const roleDefinition = roles.get(role);
if (!roleDefinition || roleDefinition.abstract) {
continue;
}
// Semantic-role elements expose required ARIA state natively — skip.
if (isSemanticRoleElement(node, role, context)) {
return { role, missing: null };
}
const requiredAttributes = Object.keys(roleDefinition.requiredProps);
const missingRequiredAttributes = requiredAttributes
.filter((requiredAttribute) => !foundAriaAttributes.includes(requiredAttribute))
// Sort for deterministic report order (aria-query's requiredProps
// iteration order is not guaranteed stable across versions).
.sort();
return {
role,
missing: missingRequiredAttributes.length > 0 ? missingRequiredAttributes : null,
};
Comment thread
johanrd marked this conversation as resolved.
}
return null;
}

/** @type {import('eslint').Rule.RuleModule} */
Expand Down Expand Up @@ -83,38 +225,38 @@ module.exports = {

return {
GlimmerElementNode(node) {
const role = getStaticRoleFromElement(node);
const roleTokens = getStaticRolesFromElement(node);

if (!role) {
if (!roleTokens) {
return;
}

const foundAriaAttributes = (node.attributes ?? [])
.filter((attribute) => attribute.name?.startsWith('aria-'))
.map((attribute) => attribute.name);

const missingRequiredAttributes = getMissingRequiredAttributes(role, foundAriaAttributes);
const result = getMissingRequiredAttributes(roleTokens, foundAriaAttributes, node, context);

if (missingRequiredAttributes) {
reportMissingAttributes(node, role, missingRequiredAttributes);
if (result?.missing) {
reportMissingAttributes(node, result.role, result.missing);
}
},

GlimmerMustacheStatement(node) {
const role = getStaticRoleFromMustache(node);
const roleTokens = getStaticRolesFromMustache(node);

if (!role) {
if (!roleTokens) {
return;
}

const foundAriaAttributes = (node.hash?.pairs ?? [])
.filter((pair) => pair.key.startsWith('aria-'))
.map((pair) => pair.key);

const missingRequiredAttributes = getMissingRequiredAttributes(role, foundAriaAttributes);
const result = getMissingRequiredAttributes(roleTokens, foundAriaAttributes, node, context);

if (missingRequiredAttributes) {
reportMissingAttributes(node, role, missingRequiredAttributes);
if (result?.missing) {
reportMissingAttributes(node, result.role, result.missing);
}
},
};
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"dependencies": {
"@ember-data/rfc395-data": "^0.0.4",
"aria-query": "^5.3.2",
"axobject-query": "^4.1.0",
"css-tree": "^3.0.1",
"editorconfig": "^3.0.2",
"ember-eslint-parser": "^0.10.0",
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading