Skip to content

Commit

Permalink
refactor to match the eslint-plugin-jsx-a11y implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
tanhauhau committed Jul 11, 2022
1 parent 751d927 commit 5bdc92e
Show file tree
Hide file tree
Showing 10 changed files with 986 additions and 633 deletions.
16 changes: 16 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -132,6 +132,7 @@
"acorn": "^8.4.1",
"agadoo": "^1.1.0",
"aria-query": "^5.0.0",
"axobject-query": "^3.0.1",
"code-red": "^0.2.5",
"css-tree": "^1.1.2",
"eslint": "^8.0.0",
Expand Down
11 changes: 11 additions & 0 deletions site/content/docs/05-accessibility-warnings.md
Expand Up @@ -250,6 +250,17 @@ Some HTML elements have default ARIA roles. Giving these elements an ARIA role t

---

### `a11y-no-interactive-element-to-noninteractive-role`

[WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) roles should not be used to convert an interactive element to a non-interactive element. Non-interactive ARIA roles include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.

```sv
<!-- A11y: <textarea> cannot have role 'listitem' -->
<textarea role="listitem" />
```

---

### `a11y-positive-tabindex`

Avoid positive `tabindex` property values. This will move elements out of the expected tab order, creating a confusing experience for keyboard users.
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/compile/compiler_warnings.ts
Expand Up @@ -111,6 +111,10 @@ export default {
code: 'a11y-no-redundant-roles',
message: `A11y: Redundant role '${role}'`
}),
a11y_no_interactive_element_to_noninteractive_role: (role: string | boolean, element: string) => ({
code: 'a11y-no-interactive-element-to-noninteractive-role',
message: `A11y: <${element}> cannot have role '${role}'`
}),
a11y_role_has_required_aria_props: (role: string, props: string[]) => ({
code: 'a11y-role-has-required-aria-props',
message: `A11y: Elements with the ARIA role "${role}" must have the following attributes defined: ${props.map(name => `"${name}"`).join(', ')}`
Expand Down
31 changes: 14 additions & 17 deletions src/compiler/compile/nodes/Element.ts
Expand Up @@ -24,15 +24,14 @@ import { Literal } from 'estree';
import compiler_warnings from '../compiler_warnings';
import compiler_errors from '../compiler_errors';
import { ARIARoleDefintionKey, roles, aria, ARIAPropertyDefinition, ARIAProperty } from 'aria-query';
import { noninteractive_roles } from '../utils/aria_roles';
import { interactive_elements } from '../utils/elements';
import { is_interactive_element, is_non_interactive_roles, is_presentation_role } from '../utils/a11y';

const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|svg|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;

const aria_attributes = 'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split(' ');
const aria_attribute_set = new Set(aria_attributes);

const aria_roles = 'alert alertdialog application article banner blockquote button caption cell checkbox code columnheader combobox complementary contentinfo definition deletion dialog directory document emphasis feed figure form generic graphics-document graphics-object graphics-symbol grid gridcell group heading img link list listbox listitem log main marquee math meter menu menubar menuitem menuitemcheckbox menuitemradio navigation none note option paragraph presentation progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox separator slider spinbutton status strong subscript superscript switch tab table tablist tabpanel term textbox time timer toolbar tooltip tree treegrid treeitem'.split(' ');
const aria_roles = roles.keys();
const aria_role_set = new Set(aria_roles);

const a11y_required_attributes = {
Expand Down Expand Up @@ -438,6 +437,11 @@ export default class Element extends Node {
validate_attributes_a11y() {
const { component, attributes } = this;

const attribute_map = new Map<string, Attribute>();
attributes.forEach(attribute => (
attribute_map.set(attribute.name, attribute)
));

attributes.forEach(attribute => {
if (attribute.is_spread) return;

Expand Down Expand Up @@ -480,7 +484,7 @@ export default class Element extends Node {
component.warn(attribute, compiler_warnings.a11y_misplaced_role(this.name));
}

const value = attribute.get_static_value();
const value = attribute.get_static_value() as ARIARoleDefintionKey;
// @ts-ignore
if (value && !aria_role_set.has(value)) {
// @ts-ignore
Expand All @@ -505,7 +509,7 @@ export default class Element extends Node {
}

// role-has-required-aria-props
const role = roles.get(value as ARIARoleDefintionKey);
const role = roles.get(value);
if (role) {
const required_role_props = Object.keys(role.requiredProps);
const has_missing_props = required_role_props.some(prop => !attributes.find(a => a.name === prop));
Expand All @@ -514,6 +518,11 @@ export default class Element extends Node {
component.warn(attribute, compiler_warnings.a11y_role_has_required_aria_props(value as string, required_role_props));
}
}

// no-interactive-element-to-noninteractive-role
if (is_interactive_element(this.name, attribute_map) && (is_non_interactive_roles(value) || is_presentation_role(value))) {
component.warn(this, compiler_warnings.a11y_no_interactive_element_to_noninteractive_role(value, this.name));
}
}

// no-access-key
Expand Down Expand Up @@ -683,18 +692,6 @@ export default class Element extends Node {
if (handlers_map.has('mouseout') && !handlers_map.has('blur')) {
component.warn(this, compiler_warnings.a11y_mouse_events_have_key_events('mouseout', 'blur'));
}

if (interactive_elements.has(this.name)) {
if (attribute_map.has('role')) {
const roleValue = this.attributes.find(a => a.name === 'role').get_static_value().toString() as ARIARoleDefintionKey;
if (noninteractive_roles.has(roleValue)) {
component.warn(this, {
code: 'a11y-no-interactive-element-to-noninteractive-role',
message: `A11y: <${this.name}> cannot have role ${roleValue}`
});
}
}
}
}

validate_bindings_foreign() {
Expand Down
137 changes: 137 additions & 0 deletions src/compiler/compile/utils/a11y.ts
@@ -0,0 +1,137 @@
import {
ARIARoleDefintionKey,
roles as roles_map,
elementRoles,
ARIARoleRelationConcept
} from 'aria-query';
import { AXObjects, elementAXObjects } from 'axobject-query';
import Attribute from '../nodes/Attribute';

const roles = [...roles_map.keys()];

const non_interactive_roles = new Set(
roles
.filter((name) => {
const role = roles_map.get(name);
return (
!roles_map.get(name).abstract &&
// 'toolbar' does not descend from widget, but it does support
// aria-activedescendant, thus in practice we treat it as a widget.
name !== 'toolbar' &&
!role.superClass.some((classes) => classes.includes('widget'))
);
})
.concat(
// The `progressbar` is descended from `widget`, but in practice, its
// value is always `readonly`, so we treat it as a non-interactive role.
'progressbar'
)
);

const interactive_roles = new Set(
roles
.filter((name) => {
const role = roles_map.get(name);
return (
!role.abstract &&
// The `progressbar` is descended from `widget`, but in practice, its
// value is always `readonly`, so we treat it as a non-interactive role.
name !== 'progressbar' &&
role.superClass.some((classes) => classes.includes('widget'))
);
})
.concat(
// 'toolbar' does not descend from widget, but it does support
// aria-activedescendant, thus in practice we treat it as a widget.
'toolbar'
)
);

export function is_non_interactive_roles(role: ARIARoleDefintionKey) {
return non_interactive_roles.has(role);
}

const presentation_roles = new Set(['presentation', 'none']);

export function is_presentation_role(role: ARIARoleDefintionKey) {
return presentation_roles.has(role);
}

const non_interactive_element_role_schemas: ARIARoleRelationConcept[] = [];

elementRoles.entries().forEach(([schema, roles]) => {
if ([...roles].every((role) => non_interactive_roles.has(role))) {
non_interactive_element_role_schemas.push(schema);
}
});

const interactive_element_role_schemas: ARIARoleRelationConcept[] = [];

elementRoles.entries().forEach(([schema, roles]) => {
if ([...roles].every((role) => interactive_roles.has(role))) {
interactive_element_role_schemas.push(schema);
}
});

const interactive_ax_objects = new Set(
[...AXObjects.keys()].filter((name) => AXObjects.get(name).type === 'widget')
);

const interactive_element_ax_object_schemas: ARIARoleRelationConcept[] = [];

elementAXObjects.entries().forEach(([schema, ax_object]) => {
if ([...ax_object].every((role) => interactive_ax_objects.has(role))) {
interactive_element_ax_object_schemas.push(schema);
}
});

function match_schema(
schema: ARIARoleRelationConcept,
tag_name: string,
attribute_map: Map<string, Attribute>
) {
if (schema.name !== tag_name) return false;
if (!schema.attributes) return true;
return schema.attributes.every((schema_attribute) => {
const attribute = attribute_map.get(schema_attribute.name);
if (!attribute) return false;
if (
schema_attribute.value &&
schema_attribute.value !== attribute.get_static_value()
) {
return false;
}
return true;
});
}

export function is_interactive_element(
tag_name: string,
attribute_map: Map<string, Attribute>
): boolean {
if (
interactive_element_role_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return true;
}

if (
non_interactive_element_role_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return false;
}

if (
interactive_element_ax_object_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return true;
}

return false;
}
9 changes: 0 additions & 9 deletions src/compiler/compile/utils/aria_roles.ts

This file was deleted.

5 changes: 0 additions & 5 deletions src/compiler/compile/utils/elements.ts

This file was deleted.

0 comments on commit 5bdc92e

Please sign in to comment.