Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 11 additions & 0 deletions .changeset/shy-sites-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@biomejs/biome": patch
---

Added the nursery rule [`noAmbiguousAnchorText`](https://biomejs.dev/linter/rules/no-ambiguous-anchor-text/), which disallows ambiguous anchor descriptions.

#### Invalid

```html
<a>learn more</a>
```
12 changes: 12 additions & 0 deletions crates/biome_cli/src/execute/migrate/eslint_any_rule_to_biome.rs

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

277 changes: 149 additions & 128 deletions crates/biome_configuration/src/analyzer/linter/rules.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/biome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ define_categories! {
"lint/correctness/useValidForDirection": "https://biomejs.dev/linter/rules/use-valid-for-direction",
"lint/correctness/useValidTypeof": "https://biomejs.dev/linter/rules/use-valid-typeof",
"lint/correctness/useYield": "https://biomejs.dev/linter/rules/use-yield",
"lint/nursery/noAmbiguousAnchorText": "https://biomejs.dev/linter/rules/no-ambiguous-anchor-text",
"lint/nursery/noColorInvalidHex": "https://biomejs.dev/linter/rules/no-color-invalid-hex",
"lint/nursery/noContinue": "https://biomejs.dev/linter/rules/no-continue",
"lint/nursery/noDeprecatedImports": "https://biomejs.dev/linter/rules/no-deprecated-imports",
Expand Down
22 changes: 22 additions & 0 deletions crates/biome_html_analyze/src/a11y.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use biome_html_syntax::element_ext::AnyHtmlTagElement;

/// Check the element is hidden from screen reader.
///
/// Ref:
/// - https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden
/// - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden
/// - https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/v6.10.0/src/util/isHiddenFromScreenReader.js
pub(crate) fn is_hidden_from_screen_reader(element: &AnyHtmlTagElement) -> bool {
let is_aria_hidden = element.has_truthy_attribute("aria-hidden");
if is_aria_hidden {
return true;
}

match element.name_value_token().ok() {
Some(name) if name.text_trimmed() == "input" => element
.find_attribute_by_name("type")
.and_then(|attribute| attribute.initializer()?.value().ok()?.string_value())
.is_some_and(|value| value.text() == "hidden"),
_ => false,
}
}
1 change: 1 addition & 0 deletions crates/biome_html_analyze/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![deny(clippy::use_self)]

mod a11y;
mod lint;
pub mod options;
mod registry;
Expand Down
3 changes: 2 additions & 1 deletion crates/biome_html_analyze/src/lint/nursery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! Generated file, do not edit by hand, see `xtask/codegen`

use biome_analyze::declare_lint_group;
pub mod no_ambiguous_anchor_text;
pub mod no_script_url;
pub mod no_sync_scripts;
pub mod no_vue_v_if_with_v_for;
Expand All @@ -14,4 +15,4 @@ pub mod use_vue_valid_v_html;
pub mod use_vue_valid_v_if;
pub mod use_vue_valid_v_on;
pub mod use_vue_valid_v_text;
declare_lint_group! { pub Nursery { name : "nursery" , rules : [self :: no_script_url :: NoScriptUrl , self :: no_sync_scripts :: NoSyncScripts , self :: no_vue_v_if_with_v_for :: NoVueVIfWithVFor , self :: use_vue_hyphenated_attributes :: UseVueHyphenatedAttributes , self :: use_vue_valid_v_bind :: UseVueValidVBind , self :: use_vue_valid_v_else :: UseVueValidVElse , self :: use_vue_valid_v_else_if :: UseVueValidVElseIf , self :: use_vue_valid_v_html :: UseVueValidVHtml , self :: use_vue_valid_v_if :: UseVueValidVIf , self :: use_vue_valid_v_on :: UseVueValidVOn , self :: use_vue_valid_v_text :: UseVueValidVText ,] } }
declare_lint_group! { pub Nursery { name : "nursery" , rules : [self :: no_ambiguous_anchor_text :: NoAmbiguousAnchorText , self :: no_script_url :: NoScriptUrl , self :: no_sync_scripts :: NoSyncScripts , self :: no_vue_v_if_with_v_for :: NoVueVIfWithVFor , self :: use_vue_hyphenated_attributes :: UseVueHyphenatedAttributes , self :: use_vue_valid_v_bind :: UseVueValidVBind , self :: use_vue_valid_v_else :: UseVueValidVElse , self :: use_vue_valid_v_else_if :: UseVueValidVElseIf , self :: use_vue_valid_v_html :: UseVueValidVHtml , self :: use_vue_valid_v_if :: UseVueValidVIf , self :: use_vue_valid_v_on :: UseVueValidVOn , self :: use_vue_valid_v_text :: UseVueValidVText ,] } }
194 changes: 194 additions & 0 deletions crates/biome_html_analyze/src/lint/nursery/no_ambiguous_anchor_text.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
use biome_analyze::{
Ast, QueryMatch, Rule, RuleDiagnostic, RuleSource, context::RuleContext, declare_lint_rule,
};
use biome_console::markup;
use biome_html_syntax::{
AnyHtmlContent, AnyHtmlElement, HtmlElement, HtmlOpeningElement,
element_ext::AnyHtmlTagElement, inner_string_text,
};
use biome_rowan::AstNode;
use biome_rule_options::no_ambiguous_anchor_text::NoAmbiguousAnchorTextOptions;
use biome_string_case::StrOnlyExtension;

use crate::a11y::is_hidden_from_screen_reader;

declare_lint_rule! {
/// Disallow ambiguous anchor descriptions.
///
/// Enforces <a> values are not exact matches for the phrases "click here", "here", "link", "a link", or "learn more".
/// Screen readers announce tags as links/interactive, but rely on values for context.
/// Ambiguous anchor descriptions do not provide sufficient context for users.
///
/// ## Examples
///
/// ### Invalid
///
/// ```html,expect_diagnostic
/// <a>learn more</a>
/// ```
///
/// ### Valid
///
/// ```html
/// <a>documentation</a>
/// ```
///
/// ## Options
///
/// ### `words`
///
/// The words option allows users to modify the strings that can be checked for in the anchor text. Useful for specifying other words in other languages.
///
/// Default `["click here", "here", "link", "a link", "learn more"]`
///
/// ```json,options
/// {
/// "options": {
/// "words": ["click this"]
/// }
/// }
/// ```
///
/// #### Invalid
///
/// ```html,expect_diagnostic,use_options
/// <a>click this</a>
/// ```
///
pub NoAmbiguousAnchorText {
version: "next",
name: "noAmbiguousAnchorText",
language: "html",
recommended: false,
sources: &[RuleSource::EslintJsxA11y("anchor-ambiguous-text").same()],
}
}

impl Rule for NoAmbiguousAnchorText {
type Query = Ast<HtmlOpeningElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = NoAmbiguousAnchorTextOptions;

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let binding = ctx.query();
let words = ctx.options().words();

let name = binding.name().ok()?;
let value_token = name.value_token().ok()?;
if value_token.text_trimmed() != "a" {
return None;
}

let parent = HtmlElement::cast(binding.syntax().parent()?)?;
let text = get_accessible_child_text(&parent);

if words.contains(&text) {
return Some(());
}

None
}

fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let parent = node.syntax().parent()?;
Some(
RuleDiagnostic::new(
rule_category!(),
parent.text_range(),
markup! {
"No ambiguous anchor descriptions allowed."
},
)
.note(markup! {
"Ambiguous anchor descriptions do not provide sufficient context for screen reader users. Provide more context to these users."
}),
)
}
}

fn get_aria_label(node: &AnyHtmlTagElement) -> Option<String> {
let attribute = node.attributes().find_by_name("aria-label")?;
let initializer = attribute.initializer()?;
let value = initializer.value().ok()?;
let html_string = value.as_html_string()?;
let text = html_string.inner_string_text().ok()?;

Some(text.to_string())
}

fn get_img_alt(node: &AnyHtmlTagElement) -> Option<String> {
let name = node.name().ok()?;
let value_token = name.value_token().ok()?;
if value_token.text_trimmed() != "img" {
return None;
}

let attribute = node.attributes().find_by_name("alt")?;
let initializer = attribute.initializer()?;
let value = initializer.value().ok()?;
let html_string = value.as_html_string()?;
let text = html_string.inner_string_text().ok()?;

Some(text.to_string())
}

fn standardize_space_and_case(input: &str) -> String {
input
.chars()
.filter(|c| !matches!(c, ',' | '.' | '?' | '¿' | '!' | '‽' | '¡' | ';' | ':'))
.collect::<String>()
.to_lowercase_cow()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}

fn get_accessible_text(node: &AnyHtmlTagElement) -> Option<String> {
if is_hidden_from_screen_reader(node) {
return Some(String::new());
}

if let Some(aria_label) = get_aria_label(node) {
return Some(standardize_space_and_case(&aria_label));
}

if let Some(alt) = get_img_alt(node) {
return Some(standardize_space_and_case(&alt));
}

None
}

fn get_accessible_child_text(node: &HtmlElement) -> String {
if let Ok(opening) = node.opening_element() {
let any_jsx_element: AnyHtmlTagElement = opening.clone().into();
if let Some(accessible_text) = get_accessible_text(&any_jsx_element) {
return accessible_text;
}
};

let raw_child_text = node
.children()
.into_iter()
.map(|child| match child {
AnyHtmlElement::AnyHtmlContent(AnyHtmlContent::HtmlContent(content)) => {
if let Ok(value_token) = content.value_token() {
inner_string_text(&value_token).to_string()
} else {
String::new()
}
}
AnyHtmlElement::HtmlElement(element) => get_accessible_child_text(&element),
AnyHtmlElement::HtmlSelfClosingElement(element) => {
let any_jsx_element: AnyHtmlTagElement = element.clone().into();
get_accessible_text(&any_jsx_element).unwrap_or_default()
}
_ => String::new(),
})
.collect::<Vec<String>>()
.join(" ");

standardize_space_and_case(&raw_child_text)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* should generate diagnostics */

<a>here</a>

<a>HERE</a>

<a>click here</a>

<a>learn more</a>

<a>learn more</a>

<a>learn more.</a>

<a>learn more?</a>

<a>learn more,</a>

<a>learn more!</a>

<a>learn more;</a>

<a>learn more:</a>

<a>link</a>

<a>a link</a>

<a aria-label="click here">something</a>

<a> a link </a>

<a>a<i></i> link</a>

<a><i></i>a link</a>

<a><span>click</span> here</a>

<a><span> click </span> here</a>

<a><span aria-hidden>more text</span>learn more</a>

<a><span aria-hidden="true">more text</span>learn more</a>

<a><img alt="click here" /></a>

<a alt="tutorial on using eslint-plugin-jsx-a11y">click here</a>

<a><span alt="tutorial on using eslint-plugin-jsx-a11y">click here</span></a>
Loading