[java] Implement accessibility snapshots (ADR 18205)

Abierto
#18,346 7 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
35/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java

Línea de trabajo

Start by reading ADR 18205 and the tracker issue #18345, then compare the Python issue #18307 and JavaScript issue #18308 for reference behavior. The plan identifies Java APIs, remote internals, the accessibility snapshot atom, and tests under java/test/org/openqa/selenium; implementation spans these areas and requires both BiDi and Classic browser paths. Done means the proposed API and behavior are implemented and the listed corpus and browser cases pass.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

C-java I-enhancement

Part of #18345, the ADR 18205 tracker. This is the Java plan we will implement if people are happy with it. Please comment here before the PR goes up.

Python (#18307) and JavaScript (#18308) set the reference behaviour, listed in the tracker. This issue only covers how Java does it.

Public API (org.openqa.selenium)

This is a role interface, like TakesScreenshot. It is implemented by RemoteWebDriver and RemoteWebElement, so ChromeDriver, FirefoxDriver and the others get it without the Augmenter. Nothing is added to WebDriver or WebElement, so other implementations do not break.

public interface TakesAccessibilitySnapshot {

  /** Snapshot with the default options (pruned). */
  default AccessibilityNode getAccessibilitySnapshot() {
    return getAccessibilitySnapshot(AccessibilitySnapshotOptions.defaults());
  }

  /**
   * @throws StaleElementReferenceException if called on an element that is no longer attached
   */
  AccessibilityNode getAccessibilitySnapshot(AccessibilitySnapshotOptions options);
}

Options are an immutable value with withers, following ClientConfig. There is no setter-style builder, so a shared default instance can never be changed:

AccessibilitySnapshotOptions.defaults()            // interestingOnly = true
    .withInterestingOnly(false);

The node is a final class rather than a record, because we compile with --release 11. It is immutable, its collections are unmodifiable, and it has getters in the usual Selenium Java style:

public final class AccessibilityNode {
  public String getRole();                       // "text" for text leaves, "iframe" for frames
  public String getName();                       // "" when none
  public String getDescription();                // "" when none
  public Optional<String> getValue();            // textbox, searchbox, combobox, range
  public Optional<String> getUrl();              // links with an href
  public Map<String, Object> getStates();        // Boolean, Integer, or the String "mixed"; unmodifiable, ordered
  public Optional<WebElement> getElement();      // empty for text leaves and generated content
  public List<AccessibilityNode> getChildren();  // unmodifiable, [] for leaves
  public Stream<AccessibilityNode> stream();     // this node and its descendants, depth-first
  public String toText();                        // ADR §1 text form
  @Override public String toString();            // same as toText()
}

The optional fields use Optional instead of @Nullable because users read them in chains such as node.getElement().ifPresent(WebElement::click). stream() is an extra for Java. It is additive under the record's compatibility rule, and it covers the most common thing people will do with the tree:

TakesAccessibilitySnapshot snapshots = (TakesAccessibilitySnapshot) driver;
AccessibilityNode tree = snapshots.getAccessibilitySnapshot();
System.out.println(tree.toText());

tree.stream()
    .filter(n -> n.getRole().equals("button") && n.getName().equals("Submit"))
    .findFirst()
    .flatMap(AccessibilityNode::getElement)
    .ifPresent(WebElement::click);

AccessibilityNode form =
    ((TakesAccessibilitySnapshot) driver.findElement(By.id("login")))
        .getAccessibilitySnapshot(AccessibilitySnapshotOptions.defaults().withInterestingOnly(false));

Internals (org.openqa.selenium.remote, package-private)

  • AccessibilitySnapshotter is created lazily, one per RemoteWebDriver. RemoteWebElement delegates to its parent's instance.
  • BiDi path. Used when the webSocketUrl capability is present. Raw script.callFunction and browsingContext.getTree go through the driver's HasBiDi.getHandle(), wrapped in a small internal org.openqa.selenium.bidi.Module subclass. It does not use the deprecated getBiDi()/maybeGetBiDi() (ADR 17670) or the public bidi.module.Script, so taking a snapshot never warns about calls the user did not make.
  • Classic path. Uses executeScript with the atom source. Frames are reached with switchTo().frame(WebElement) and switchTo().parentFrame() in a try/finally, so the current context is restored even if a frame throws.
  • AccessibilityNode.fromWire(...) (package-private) builds the tree from the atom's JSON with org.openqa.selenium.json.Json. It maps element indexes to RemoteWebElement through the driver's element factory.
  • Frames that cannot be reached are logged at Level.FINE and become childless iframe nodes. Stale roots throw StaleElementReferenceException.
  • Atom: a copy_file of //javascript/atoms/fragments:accessibility-snapshot-wire-typescript.js into //java/src/org/openqa/selenium/remote resources. It is read once with Read.resourceAsString.

Decorators and wrappers

  • WebDriverDecorator / EventFiringDecorator proxy every interface the decorated object implements, so the new interface passes through. A test will check this, including that getElement() on a decorated driver returns a decorated element.
  • RemoteWebDriver on Grid needs nothing extra. It works with the Classic path whatever the node is, and with BiDi when the Grid gives a webSocketUrl.

Tests

  • java/test/org/openqa/selenium/AccessibilityNodeTest (small, no browser): checks toText() against every corpus .json/.txt pair, plus escaping and state order.
  • java/test/org/openqa/selenium/AccessibilitySnapshotTest (JupiterTestBase, @ParameterizedTest over index.json): for each page, pruned and unpruned, compares against the corpus, preferring .webkit files on Safari. It also ports the other cases from the Python suite: rooted at the switched frame, context unchanged, frames stitched, subtree inside a frame, stale and detached roots, usable element references, a snapshot is a copy.
  • Both paths need covering. testing/drivers/Browser.java always calls enableBiDi(), so the suite needs a Classic variant that leaves BiDi off (JavaScript did the equivalent in #18308 by honouring webSocketUrl: false). This follows the repo's preference for real browsers over mocks.

Not changing

Nothing is deprecated, because this replaces no existing call. There is no CDP path.


Generated by Claude Code

Lenguaje dominante
Java
Estrellas
34.6k
Forks
8.7k
Merge medio
1 d 16 h
PR fusionados (30 d)
107

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de SeleniumHQ/selenium

Todos los issues de SeleniumHQ/selenium

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.