Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SONARHTML-198 Create rule S6852: Elements with an interactive role should support focus #284

Merged
merged 2 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
3 changes: 3 additions & 0 deletions its/ruling/src/test/resources/expected/Web-HeaderCheck.json
Original file line number Diff line number Diff line change
Expand Up @@ -1568,6 +1568,9 @@
"project:custom/S6843.html": [
0
],
"project:custom/S6852.html": [
0
],
"project:external_webkit-jb-mr1/Examples/NetscapeCocoaPlugin/test.html": [
0
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
2,
3
],
"project:custom/S6852.html": [
1
],
"project:external_webkit-jb-mr1/LayoutTests/dom/html/level2/html/HTMLInputElement01.html": [
36
],
Expand Down
5 changes: 5 additions & 0 deletions its/ruling/src/test/resources/expected/Web-S6852.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"project:custom/S6852.html": [
1
]
}
2 changes: 1 addition & 1 deletion its/sources
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,14 @@ public static boolean isHiddenFromScreenReader(TagNode element) {
&& "hidden".equalsIgnoreCase(element.getPropertyValue("type")))
|| "true".equalsIgnoreCase(element.getPropertyValue("aria-hidden"));
}

public static boolean isDisabledElement(TagNode element) {
var disabledAttr = element.getAttribute("disabled");
if (disabledAttr != null) {
return true;
}

var ariaDisabledAttr = element.getAttribute("aria-disabled");
return "true".equalsIgnoreCase(ariaDisabledAttr);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* SonarSource HTML analyzer :: Sonar Plugin
* Copyright (c) 2010-2024 SonarSource SA and Matthijs Galesloot
* [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.html.checks.accessibility;

import static org.sonar.plugins.html.api.HtmlConstants.INTERACTIVE_ELEMENTS;
import static org.sonar.plugins.html.api.HtmlConstants.INTERACTIVE_ROLES;
import static org.sonar.plugins.html.api.HtmlConstants.KNOWN_HTML_TAGS;
import static org.sonar.plugins.html.api.HtmlConstants.NON_INTERACTIVE_ELEMENTS;
import static org.sonar.plugins.html.api.HtmlConstants.NON_INTERACTIVE_ROLES;
import static org.sonar.plugins.html.api.HtmlConstants.PRESENTATION_ROLES;
import static org.sonar.plugins.html.checks.accessibility.AccessibilityUtils.isDisabledElement;
import static org.sonar.plugins.html.checks.accessibility.AccessibilityUtils.isHiddenFromScreenReader;

import java.util.HashSet;
import java.util.Set;

import org.sonar.check.Rule;
import org.sonar.plugins.html.checks.AbstractPageCheck;
import org.sonar.plugins.html.node.TagNode;

@Rule(key = "S6852")
public class FocusableInteractiveElementsCheck extends AbstractPageCheck {

private static final String MESSAGE_TEMPLATE = "Elements with the \"%s\" interactive role must be focusable.";

private static final Set<String> INTERACTIVE_PROPS = new HashSet<>();
static {
INTERACTIVE_PROPS.addAll(EventHandlers.EVENT_HANDLERS_BY_TYPE.get("keyboard"));
INTERACTIVE_PROPS.addAll(EventHandlers.EVENT_HANDLERS_BY_TYPE.get("mouse"));
}

@Override
public void startElement(TagNode element) {
var role = element.getAttribute("role");
if (role == null) {
return;
}

if (!isHTMLTag(element)
|| !hasInteractiveProps(element)
|| !hasInteractiveRole(element)
|| isDisabledElement(element)
|| isHiddenFromScreenReader(element)
|| isInteractiveElement(element)
|| isNoninteractiveElement(element)
|| hasPresentationRole(element)
|| hasNoninteractiveRole(element)
|| element.hasProperty("tabindex")
) {
return;
}

var message = String.format(MESSAGE_TEMPLATE, role);
createViolation(element.getStartLinePosition(), message);
}

private static boolean isHTMLTag(TagNode element) {
return KNOWN_HTML_TAGS.stream().anyMatch(tag -> tag.equalsIgnoreCase(element.getNodeName()));
}

private static boolean hasInteractiveProps(TagNode element) {
return INTERACTIVE_PROPS.stream().anyMatch(prop -> {
var attr = element.getAttribute(prop);
return attr != null && !attr.isEmpty();
});
}

private static boolean hasInteractiveRole(TagNode element) {
return INTERACTIVE_ROLES.stream().anyMatch(role -> role.equalsIgnoreCase(element.getAttribute("role")));
}

private static boolean isInteractiveElement(TagNode element) {
return INTERACTIVE_ELEMENTS.stream().anyMatch(tag -> tag.equalsIgnoreCase(element.getNodeName()));
}

private static boolean isNoninteractiveElement(TagNode element) {
return NON_INTERACTIVE_ELEMENTS.stream().anyMatch(tag -> tag.equalsIgnoreCase(element.getNodeName()));
}

private static boolean hasPresentationRole(TagNode element) {
return PRESENTATION_ROLES.stream().anyMatch(role -> role.equalsIgnoreCase(element.getAttribute("role")));
}

private static boolean hasNoninteractiveRole(TagNode element) {
return NON_INTERACTIVE_ROLES.stream().anyMatch(role -> role.equalsIgnoreCase(element.getAttribute("role")));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you refactor this to use the methods from HtmlConstants.java, and move the new ones there?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import org.sonar.plugins.html.checks.accessibility.AnchorsHaveContentCheck;
import org.sonar.plugins.html.checks.accessibility.AriaProptypesCheck;
import org.sonar.plugins.html.checks.accessibility.FocusableInteractiveElementsCheck;
import org.sonar.plugins.html.checks.accessibility.ValidAutocompleteCheck;
import org.sonar.plugins.html.checks.accessibility.ImgRedundantAltCheck;
import org.sonar.plugins.html.checks.accessibility.LabelHasAssociatedControlCheck;
Expand Down Expand Up @@ -120,6 +121,7 @@ public final class CheckClasses {
FileLengthCheck.class,
FixmeCommentCheck.class,
FlashUsesBothObjectAndEmbedCheck.class,
FocusableInteractiveElementsCheck.class,
FrameWithoutTitleCheck.class,
HeaderCheck.class,
HeadingHasAccessibleContentCheck.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<p>Interactive elements being focusable is vital for website accessibility. It enables users, including those using assistive technologies, to
interact effectively with the website. Without this, some users may be unable to access certain features, leading to a poor user experience and
potential non-compliance with accessibility standards.</p>
<h2>Why is this an issue?</h2>
<p>Lack of focusability can hinder navigation and interaction with the website, resulting in an exclusionary user experience and possible violation of
accessibility guidelines.</p>
<h2>How to fix it</h2>
<p>Ensure that all interactive elements on your website can receive focus. This can be achieved by using standard HTML interactive elements, or by
assigning a <code>tabindex</code> attribute of "0" to custom interactive components.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
&lt;!-- Element with mouse/keyboard handler has no tabindex --&gt;
&lt;span onclick="submitForm();" role="button"&gt;Submit&lt;/span&gt;

&lt;!-- Anchor element without href is not focusable --&gt;
&lt;a onclick="showNextPage();" role="button"&gt;Next page&lt;/a&gt;
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
&lt;!-- Element with mouse handler has tabIndex --&gt;
&lt;span onClick="doSomething();" tabIndex="0" role="button"&gt;Submit&lt;/span&gt;

&lt;!-- Focusable anchor with mouse handler --&gt;
&lt;a href="javascript:void(0);" onClick="doSomething();"&gt; Next page &lt;/a&gt;
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> W3C - <a href="https://www.w3.org/TR/WCAG20-TECHS/H4.html">Creating a logical tab order through links, form controls, and objects</a> </li>
<li> W3C - <a href="https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav">Fundamental Keyboard Navigation Conventions</a> </li>
<li> MDN - <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role#accessibility_concerns">ARIA: button role -
Accessibility concerns</a> </li>
</ul>

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"title": "Elements with an interactive role should support focus",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"accessibility"
],
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-6852",
"sqKey": "S6852",
"scope": "All",
"quickfix": "infeasible",
"code": {
"impacts": {
"MAINTAINABILITY": "LOW",
"RELIABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"S6847",
"S6850",
"S6851",
"S6852",
"S6853",
"ServerSideImageMapsCheck",
"TableHeaderHasIdOrScopeCheck",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* SonarSource HTML analyzer :: Sonar Plugin
* Copyright (c) 2010-2024 SonarSource SA and Matthijs Galesloot
* [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.html.checks.accessibility;

import java.io.File;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.sonar.plugins.html.checks.CheckMessagesVerifierRule;
import org.sonar.plugins.html.checks.TestHelper;
import org.sonar.plugins.html.visitor.HtmlSourceCode;

class FocusableInteractiveElementsCheckTest {

@RegisterExtension
public CheckMessagesVerifierRule checkMessagesVerifier = new CheckMessagesVerifierRule();

@Test
void test() throws Exception {
HtmlSourceCode sourceCode = TestHelper.scan(
new File("src/test/resources/checks/FocusableInteractiveElementsCheck.html"),
new FocusableInteractiveElementsCheck());

checkMessagesVerifier.verify(sourceCode.getIssues())
.next().atLine(36).withMessage("Elements with the \"button\" interactive role must be focusable.")
.noMore();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!-- Ignored: Missing role -->
<Foo />

<!-- Ignored: Custom -->
<Foo role="bar" />

<!-- Ignored: No interactive props -->
<div role="foo" onBar="" />
<div role="foo" onBar />
<div role="foo" onClick />
<div role="foo" onClick="" />

<!-- Ignored: Disabled -->
<div role="button" onClick="bar()" disabled />
<div role="button" onClick="bar()" aria-disabled="true" />

<!-- Ignored: Hidden -->
<div role="button" onClick="bar()" aria-hidden="true" />

<!-- Ignored: Interactive element -->
<audio role="button" onClick="bar()" />

<!-- Ignored: Noninteractive element -->
<dialog role="button" onClick="bar()" />

<!-- Ignored: Presentation role -->
<div role="presentation" onClick="bar()" />

<!-- Ignored: Noninteractive role -->
<div role="alert" onClick="bar()" />

<!-- Ignored: tabindex -->
<div role="button" onClick="bar()" tabindex="-1" />

<!-- Noncompliant -->
<div role="button" onClick="foo" />