Skip to content

Commit

Permalink
[patch] no-redundandant-roles: allow <img src="*.svg" role="img" />
Browse files Browse the repository at this point in the history
Setting role="img" is a valid use case to work around a Safari bug for better accessibility when the source image is an SVG file.
This improvement does not account for variables in the `src` attribute but adds a valid exception for when we can parse the string.
Fixes #936
  • Loading branch information
lb- authored and ljharb committed Oct 23, 2024
1 parent daba189 commit fa9845d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions __tests__/src/rules/no-redundant-roles-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,16 @@ ruleTester.run(`${ruleName}:recommended (valid list role override)`, rule, {
{ code: '<ul role="list" />' },
{ code: '<ol role="list" />' },
{ code: '<dl role="list" />' },
{ code: '<img src="example.svg" role="img" />' },
{ code: '<svg role="img" />' },
))
.map(ruleOptionsMapperFactory(listException))
.map(parserOptionsMapper),
invalid: parsers.all([].concat(
{ code: '<ul role="list" />', errors: [expectedError('ul', 'list')] },
{ code: '<ol role="list" />', errors: [expectedError('ol', 'list')] },
{ code: '<img role="img" />', errors: [expectedError('img', 'img')] },
{ code: '<img src={someVariable} role="img" />', errors: [expectedError('img', 'img')] },
))
.map(parserOptionsMapper),
});
1 change: 1 addition & 0 deletions docs/rules/no-redundant-roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ General best practice (reference resources)
### Resources

- [ARIA Spec, ARIA Adds Nothing to Default Semantics of Most HTML Elements](https://www.w3.org/TR/using-aria/#aria-does-nothing)
- [Identifying SVG as an image](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#identifying_svg_as_an_image)
10 changes: 10 additions & 0 deletions src/util/implicitRoles/img.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,15 @@ export default function getImplicitRoleForImg(attributes) {
return '';
}

/**
* If the src attribute can be determined to be an svg, allow the role to be set to 'img'
* so that VoiceOver on Safari can be better supported.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#identifying_svg_as_an_image
* @see https://bugs.webkit.org/show_bug.cgi?id=216364
*/
const src = getProp(attributes, 'src');
if (src && getLiteralPropValue(src)?.includes('.svg')) { return ''; }

return 'img';
}

0 comments on commit fa9845d

Please sign in to comment.