accessibility

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: Apache-2.0, MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package accessibility computes the accessibility tree a browser exposes to assistive technology, from a parsed onehtml document and its style cascade: roles, accessible names and descriptions, states and properties, and the tree structure with aria-owns. Names, roles and properties follow WAI-ARIA 1.2, HTML-AAM, Core-AAM and the Accessible Name and Description Computation 1.2, and where those leave a choice, what Chrome reports.

The happy path is Tree:

doc, _ := onehtml.Parse(r)
tree, _ := accessibility.Tree(doc)
for n := range tree.Nodes() { fmt.Println(n.Role(), n.Name()) }

Nothing here runs script or fetches anything. Rendered facts from a browser, when the caller has them, refine the choices that depend on layout (WithFacts).

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<title>Shop</title>
<nav aria-label="Main"><a href="/cart">Cart</a></nav>
<main><h1>Welcome</h1><label>Email <input type=email required></label><button>Sign up</button></main>`))
	tree, _ := accessibility.Tree(doc)
	for n := range tree.Nodes() {
		if n.Ignored() || n.IsText() || n.Role() == "" {
			continue
		}
		fmt.Printf("%s %q\n", n.Role(), n.Name())
	}
}
Output:
RootWebArea "Shop"
navigation "Main"
link "Cart"
main ""
heading "Welcome"
textbox "Email"
button "Sign up"

Index

Examples

Constants

View Source
const ExportSchema = "onehtml-ax/1"

ExportSchema is the value of the schema member of AXTree.WriteChromeJSON.

Variables

View Source
var ErrFacts = errors.New("accessibility: rendered facts do not match the document")

ErrFacts is returned (wrapped) when rendered facts do not describe the document they were given with.

View Source
var ErrNoDocument = errors.New("accessibility: nil document")

ErrNoDocument is returned by Tree for a nil or zero document.

Functions

This section is empty.

Types

type AXTree

type AXTree struct {
	// contains filtered or unexported fields
}

AXTree is the accessibility tree of one document under one style context. It is immutable once built and safe for concurrent reads.

func Tree

func Tree(doc *onehtml.Document, opts ...Option) (*AXTree, error)

Tree builds the accessibility tree of the document.

It uses the document's cascade under the default style context unless WithStyles or WithStyleContext say otherwise. The tree keeps ignored nodes, each with its reasons, and their children stay their children; use AXTree.Nodes with Node.Ignored to prune. Tree returns an error only for rendered facts that do not match the document, or ErrNoDocument for a nil or zero document.

Tree takes no context.Context: the work is CPU-bound and limited (the document's size limits and WithMaxNameWork) and there is nothing to wait for. To stop early, run it in a goroutine and drop the result.

func (*AXTree) Description

func (t *AXTree) Description(n onehtml.Node) string

Description returns the accessible description of any element.

func (*AXTree) Diagnostics

func (t *AXTree) Diagnostics() []Diagnostic

Diagnostics lists what the tree builder noticed about the page, in tree order; see Diagnostic for the kinds. It is computed once.

func (*AXTree) Diff

func (t *AXTree) Diff(later *AXTree, cs *onehtml.ChangeSet) *TreeDiff

Diff compares the receiver with a later tree of the same document or of an edited snapshot of it. Nodes are matched by identity: the DOM node, whose index survives edits; cs, when given, is the change set between the two snapshots, and lets a text node that an edit replaced match its successor. Either tree nil or empty counts as having no nodes.

func (*AXTree) Document

func (t *AXTree) Document() *onehtml.Document

Document returns the document the tree describes.

func (*AXTree) ElementRole

func (t *AXTree) ElementRole(n onehtml.Node, options ...RoleOption) RoleReport

ElementRole reports the role layer's view of an element of the document: its role and where it came from, state, native ARIA properties, and the problems with its role and aria-* attributes. Elements the tree leaves out are reported too. A node that is not an element of the tree's document gets the zero report.

Example

The role layer reports how a role was reached and what is wrong with the role and aria attributes.

package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<div role="bogus button" aria-checked=true>x</div>`))
	tree, _ := accessibility.Tree(doc)
	for el := range doc.Root().Descendants() {
		if el.Is("div") {
			r := tree.ElementRole(el)
			fmt.Println(r.Role, r.Origin, r.Explicit)
			for _, d := range r.Diagnostics {
				fmt.Println(d.Kind, d.Attribute)
			}
		}
	}
}
Output:
button explicit button
invalid-role-token role
unsupported-attribute aria-checked

func (*AXTree) FocusOrder

func (t *AXTree) FocusOrder() iter.Seq[onehtml.Node]

FocusOrder iterates the elements sequential keyboard navigation visits: those with a positive tabindex in ascending order (document order breaks ties), then the other tabbable elements in document order.

Example

Keyboard focus: a positive tabindex goes first, then document order.

package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<a href=1>one</a><button>two</button><div tabindex=1>three</div>`))
	tree, _ := accessibility.Tree(doc)
	for el := range tree.FocusOrder() {
		fmt.Println(el.Name(), el.TextContent())
	}
}
Output:
div three
a one
button two

func (*AXTree) Hidden

func (t *AXTree) Hidden(n onehtml.Node) Hidden

Hidden reports whether and why an element of the document is hidden.

func (*AXTree) Len

func (t *AXTree) Len() int

Len returns the number of nodes, ignored ones included.

func (*AXTree) LimitReached

func (t *AXTree) LimitReached() bool

LimitReached reports whether a work limit cut a name short.

func (*AXTree) Name

func (t *AXTree) Name(n onehtml.Node) string

Name returns the accessible name of any element of the document, whether or not it has a node in the tree: an element that is hidden or ignored still has the name the algorithm gives it.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<span id=n>Billing</span> <input id=f aria-labelledby=n placeholder="ignored">`))
	tree, _ := accessibility.Tree(doc)
	field, _ := doc.SelectFirst("#f")
	fmt.Println(tree.Name(field))
}
Output:
Billing

func (*AXTree) NavigationLists

func (t *AXTree) NavigationLists() *NavigationLists

NavigationLists builds the navigation lists of the tree.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<nav aria-label="Site"><a href="#top">Top</a></nav><h1>Title</h1><h2>Part</h2>`))
	tree, _ := accessibility.Tree(doc)
	nl := tree.NavigationLists()
	for _, h := range nl.Headings {
		fmt.Println("heading", h.Level, h.Name)
	}
	for _, l := range nl.Landmarks {
		fmt.Println("landmark", l.Role, l.Name)
	}
	for _, l := range nl.Links {
		fmt.Println("link", l.Name, l.SamePage)
	}
}
Output:
heading 1 Title
heading 2 Part
landmark navigation Site
link Top true

func (*AXTree) NodeFor

func (t *AXTree) NodeFor(n onehtml.Node) (Node, bool)

NodeFor returns the tree node of a DOM node, and false when it has none (it is not rendered, or the tree leaves it out).

func (*AXTree) Nodes

func (t *AXTree) Nodes() iter.Seq[Node]

Nodes yields every node in tree order (pre-order), the document node first. Ignored nodes are included; their children follow them.

func (*AXTree) ReadingView

func (t *AXTree) ReadingView() *ReadingView

ReadingView builds the reading view of the tree. Hidden and aria-hidden content is not read; ignored nodes produce no step, but their children are visited.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<main><h1>News</h1><p>Hello <a href="/more">more</a></p><ul><li>one<li>two</ul></main>`))
	tree, _ := accessibility.Tree(doc)
	fmt.Println(tree.ReadingView())
}
Output:
> main landmark
  E heading level 1: News
  T Hello
  E link: more
  > list with 2 items
    E item 1 of 2
    T one
    E item 2 of 2
    T two
  < end of list
< end of main landmark

func (*AXTree) Root

func (t *AXTree) Root() Node

Root returns the node of the document.

func (*AXTree) Update

func (t *AXTree) Update(cs *onehtml.ChangeSet, styles *onehtml.Styles) (*AXTree, error)

Update returns the tree of the edited document cs.New. It equals Tree on that document with the options this tree was built with and the cascade styles (nil: the receiver's cascade restyled through cs). The receiver is not changed.

This version always builds the tree afresh, so UpdateInfo reports Incremental false with the reason. Update returns onehtml.ErrStaleChanges when cs does not start at the receiver's document, and ErrFacts when the receiver was built with rendered facts, which describe only the old snapshot.

func (*AXTree) UpdateInfo

func (t *AXTree) UpdateInfo() UpdateInfo

UpdateInfo reports how the tree was made when it came from AXTree.Update or AXTree.WithContext; any other tree reports the zero value.

func (*AXTree) WithContext

func (t *AXTree) WithContext(ctx onehtml.StyleContext) *AXTree

WithContext returns the tree of the same document under another style context (the focused element, the viewport, the colour scheme). It equals Tree with WithStyleContext(ctx) and the other options of the receiver. A nil or zero tree answers nil.

func (*AXTree) WriteChromeJSON

func (t *AXTree) WriteChromeJSON(w io.Writer, options ...ExportOption) error

WriteChromeJSON writes the tree in the shape of Chrome's Accessibility.getFullAXTree result under a schema member:

{"schema":"onehtml-ax/1","nodes":[...]}

Nodes come in tree order. Each has nodeId (the tree index as a string), ignored, role, parentId and childIds; an ignored node has the role none and its ignoredReasons; other nodes have name (with the one source that supplied it), description when not empty, value and properties in a fixed order. backendDOMNodeId is the document's node index and is absent for the document and for nodes made up from layout. The output is deterministic. InlineTextBox nodes are not part of the tree, so none is written.

Example

The export has Chrome's getFullAXTree shape under a schema name.

package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<button>Go</button>`))
	tree, _ := accessibility.Tree(doc)
	var buf bytes.Buffer
	_ = tree.WriteChromeJSON(&buf)
	fmt.Println(buf.Len() > 0, bytes.HasPrefix(buf.Bytes(), []byte(`{"schema":"onehtml-ax/1"`)))
}
Output:
true true

type AttrCheck

type AttrCheck uint8

AttrCheck says how strictly the attributes of the snapshot must match the document's when Facts.Map pairs them.

const (
	// AttrValues (the default): every element has the same attribute names
	// with the same values, in any order.
	AttrValues AttrCheck = iota
	// AttrNames: the same attribute names; values may differ (a script may
	// have changed them).
	AttrNames
	// AttrNone: attributes are not compared.
	AttrNone
)

type Background

type Background struct {
	Median, P5, P95 Color
}

Background is the sampled background colour behind a node: the median of the sampled pixels and the 5th and 95th percentiles.

type BackgroundSamples

type BackgroundSamples struct {
	// contains filtered or unexported fields
}

BackgroundSamples are background colours measured behind elements, read by ParseBackgroundSamples.

func ParseBackgroundSamples

func ParseBackgroundSamples(b []byte) (*BackgroundSamples, error)

ParseBackgroundSamples reads a samples document:

{"format":"onehtml-background-samples","version":1,
 "viewport":{"width":1280,"height":800},
 "samples":[{"backendNodeId":9,"median":"#102030","p5":"#fff","p95":"rgb(0,0,0)","pixels":42}]}

A sample names its element by backendNodeId or, without one, by snapshotNode; colours are #rgb, #rgba, #rrggbb, #rrggbbaa, rgb() and rgba() with comma-separated numbers. p5 and p95 default to the median. Unknown members are ignored. Anything else is a *FactsError of Kind "format".

Example

Background samples attach measured colours to elements by node id.

facts, _ := accessibility.ParseFacts([]byte(factsSnap), nil)
doc, _ := onehtml.ParseBytes([]byte(`<body id=x>hi`))
m, _ := facts.Map(doc)
bs, err := accessibility.ParseBackgroundSamples([]byte(`{"format":"onehtml-background-samples","version":1,
	  "samples":[{"backendNodeId":4,"median":"#003366"}]}`))
if err != nil {
	panic(err)
}
m, applied, unmatched, _ := m.WithBackgroundSamples(bs)
for el := range doc.Root().Descendants() {
	if el.Is("body") {
		nf, _ := m.Node(el)
		fmt.Println(applied, unmatched, nf.Background.Median)
	}
}
Output:
1 0 {0 51 102 1}

type BoxFact

type BoxFact struct {
	// Element is the element of the document the box belongs to.
	Element onehtml.Node
	// BorderBox is x, y, width and height in CSS pixels.
	BorderBox [4]float64
}

BoxFact says an element has a layout box.

type Color

type Color struct {
	R, G, B uint8
	A       float64
}

Color is an sRGB colour with an alpha of 0 to 1.

type Diagnostic

type Diagnostic struct {
	// Kind is one of "role" (an ID reference that names nothing),
	// "broken-id-reference" (aria-controls, aria-details, aria-errormessage,
	// aria-flowto, aria-activedescendant or list names an element that has no
	// node in the tree), "missing-required-context",
	// "missing-required-owned-elements", "focusable-under-aria-hidden",
	// "nameless-interactive", "empty-name-required", "aria-owns-ignored" and
	// "limit-exceeded".
	Kind string
	// Node is the element concerned; the zero Node for "limit-exceeded".
	Node onehtml.Node
	// Attribute is the attribute concerned, when there is one.
	Attribute string
}

Diagnostic is one finding about the tree.

type ExportOption

type ExportOption func(*exportConfig)

ExportOption configures AXTree.WriteChromeJSON.

func WithIndent

func WithIndent(on bool) ExportOption

WithIndent writes the JSON indented by two spaces (default: one line).

type Facts

type Facts struct {
	// contains filtered or unexported fields
}

Facts are what a browser's layout said about a page: a DOMSnapshot capture (Chrome DevTools Protocol, DOMSnapshot.captureSnapshot, protocol 1.3) of the same document under the same viewport. They let the tree make the choices a browser makes only once layout is known (which generic containers it leaves out, layout tables, list markers); see WithFacts. A Facts value is immutable and safe to share.

func FactsFromBoxes

func FactsFromBoxes(doc *onehtml.Document, boxes []BoxFact) (*Facts, error)

FactsFromBoxes builds Facts for doc from boxes alone, for a renderer that is not a browser: an element with a box is drawn, an element with none is treated as display: none by the layout-aware choices of the tree, and the non-blank text of a drawn element is drawn inside its box. No computed styles are carried, so the choices that read a style (list markers, generated boxes) are not made. An element given twice keeps its last box; nodes of another document are ignored.

func ParseFacts

func ParseFacts(b []byte, computedStyles []string, options ...FactsOption) (*Facts, error)

ParseFacts reads a DOMSnapshot.captureSnapshot result, given as the snapshot itself (the object with "documents" and "strings"), as a protocol response ({"result": snapshot}) or as a capture record ({"format": {...}, "snapshot": snapshot}). computedStyles lists the property names the capture asked for, in order; when it is nil a capture record's own list is used. Malformed input is a *FactsError of Kind "format" and an exceeded limit one of Kind "limit"; nothing panics. Without options the limits of FactsLimits apply.

A capture record must say method captureSnapshot and a protocol version 1.x. The first document is the page's; Facts.Map can use another.

Example

Layout facts are a Chrome DOMSnapshot capture of the same page. They let the tree make choices that depend on layout: here the capture has no box for the empty div, so the tree leaves it out. A capture of another document is an error.

package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	const snapshot = `{"documents":[{
	  "nodes":{"parentIndex":[-1,0,1,1,3],"nodeType":[9,1,1,1,1],"nodeName":[0,1,2,3,4],"nodeValue":[-1,-1,-1,-1,-1],"backendNodeId":[1,2,3,4,5]},
	  "layout":{"nodeIndex":[1,3],"styles":[[],[]],"bounds":[[0,0,100,100],[0,0,100,100]],"text":[-1,-1]},
	  "textBoxes":{"layoutIndex":[]}}],
	  "strings":["#document","HTML","HEAD","BODY","DIV"]}`
	facts, err := accessibility.ParseFacts([]byte(snapshot), nil)
	if err != nil {
		panic(err)
	}
	doc, _ := onehtml.ParseBytes([]byte(`<div></div>`))
	plain, _ := accessibility.Tree(doc)
	withFacts, err := accessibility.Tree(doc, accessibility.WithFacts(facts))
	fmt.Println(plain.Len(), withFacts.Len(), err)

	other, _ := onehtml.ParseBytes([]byte(`<p>not the captured page</p>`))
	_, err = accessibility.Tree(other, accessibility.WithFacts(facts))
	fmt.Println(err != nil)
}
Output:
4 3 <nil>
true

func (*Facts) Documents

func (f *Facts) Documents() []FactsDocument

Documents describes every document of the snapshot, the page's first.

func (*Facts) Map

func (f *Facts) Map(doc *onehtml.Document, options ...MapOption) (*FactsMap, error)

Map pairs the snapshot's nodes with doc's, in document order. It refuses (a *FactsError of Kind "refused", matching ErrFacts) a document that is not the one the browser captured: reasons "document-index-out-of-range", "node-count-mismatch", "structure-mismatch", "text-mismatch" and "attribute-mismatch".

Example

Mapping a snapshot onto the page gives the layout box of each element.

facts, err := accessibility.ParseFacts([]byte(factsSnap), nil)
if err != nil {
	panic(err)
}
doc, _ := onehtml.ParseBytes([]byte(`<body id=x>hi`))
m, err := facts.Map(doc)
if err != nil {
	panic(err)
}
for el := range doc.Root().Descendants() {
	if el.Is("body") {
		nf, _ := m.Node(el)
		fmt.Println(nf.HasLayout, nf.BorderBox)
	}
}
fmt.Println(m.Accounting().IsComplete)

// A page that is not the captured one is refused, with a reason.
other, _ := onehtml.ParseBytes([]byte(`<body id=x>ho`))
_, err = facts.Map(other)
fmt.Println(err)
Output:
true [1 2 30 40]
true
accessibility: a text node differs from the snapshot's

func (*Facts) Product

func (f *Facts) Product() string

Product is the browser that made the capture ("Chrome/156..."), or "" when the facts were read from a bare snapshot.

func (*Facts) ProtocolVersion

func (f *Facts) ProtocolVersion() string

ProtocolVersion is the DevTools protocol version of the capture, or "".

func (*Facts) TotalNodeCount

func (f *Facts) TotalNodeCount() int

TotalNodeCount is the number of snapshot nodes in all documents.

type FactsAccounting

type FactsAccounting struct {
	// TotalNodes is the number of snapshot nodes in all documents, and
	// LayoutItems the number of layout items of the mapped document of layout items.
	TotalNodes, LayoutItems int
	// Every layout item is counted once: LayoutMapped (the first item of a
	// node paired with a document node), LayoutDuplicate (a further item of
	// such a node, such as generated text), LayoutPseudo (an item of a
	// ::before, ::after or ::marker box), LayoutShadow (inside a shadow tree
	// or a template) or LayoutUnmapped (anything else).
	LayoutMapped, LayoutDuplicate, LayoutPseudo, LayoutShadow, LayoutUnmapped int
	// IsComplete is true when no layout item is unmapped.
	IsComplete bool
}

FactsAccounting says what became of the snapshot's nodes and layout items.

type FactsDocument

type FactsDocument struct {
	NodeCount, LayoutCount, TextBoxCount int
	URL, BaseURL, Title, Language        string
	// Encoding is the document's character encoding as the browser names it.
	Encoding                    string
	ContentWidth, ContentHeight float64
}

FactsDocument describes one document of a snapshot.

type FactsError

type FactsError struct {
	// Kind is "format" (the input is not a snapshot), "limit" (a limit of
	// [FactsLimits] was exceeded) or "refused" (a valid snapshot that does
	// not describe the document or viewport it was given).
	Kind string
	// Limit names the exceeded limit, for Kind "limit".
	Limit string
	// Reason is the short code of a refusal, for Kind "refused":
	// "document-index-out-of-range", "node-count-mismatch",
	// "structure-mismatch", "text-mismatch", "attribute-mismatch" or
	// "viewport-mismatch".
	Reason string
	Msg    string
}

FactsError is the error of reading or mapping facts. It matches ErrFacts with errors.Is, and a Kind of "limit" also matches onehtml.ErrLimit.

func (*FactsError) Error

func (e *FactsError) Error() string

Error implements error. A limit error's text begins with the limit's name and a colon.

func (*FactsError) Is

func (e *FactsError) Is(target error) bool

Is matches ErrFacts, and onehtml.ErrLimit for a limit.

type FactsLimits

type FactsLimits struct {
	MaxInputBytes         int // default 256 MiB
	MaxJSONDepth          int // default 64
	MaxDocuments          int // default 64
	MaxStrings            int // default 4,194,304
	MaxStringChars        int // default 16,777,216 (in bytes)
	MaxNodes              int // per document, default 4,194,304
	MaxLayoutNodes        int // per document, default 4,194,304
	MaxTextBoxes          int // per document, default 4,194,304
	MaxArrayElements      int // longest single array, default 16,777,216
	MaxNodeDepth          int // depth of the node tree, default 4096
	MaxComputedStyleNames int // default 1024
}

FactsLimits bound what ParseFacts accepts. A field of zero uses its default; a negative field is a limit of zero (none of the thing is allowed). Every limit is checked before the work it guards, and a limit error names the field.

type FactsMap

type FactsMap struct {
	// contains filtered or unexported fields
}

FactsMap is a snapshot paired with one document, node by node. It is immutable and safe for concurrent reads.

func (*FactsMap) Accounting

func (m *FactsMap) Accounting() FactsAccounting

Accounting reports what became of the snapshot's layout items.

func (*FactsMap) DrawnText

func (m *FactsMap) DrawnText(n onehtml.Node) (string, bool)

DrawnText returns the text the browser laid out for a text node, after style transforms and white-space collapsing, and false when the text node has no layout (it was not drawn).

func (*FactsMap) Node

func (m *FactsMap) Node(n onehtml.Node) (NodeFacts, bool)

Node returns the facts about a node of the mapped document; false when the snapshot has no counterpart for it (a comment, say).

func (*FactsMap) SnapshotNode

func (m *FactsMap) SnapshotNode(n onehtml.Node) (int, bool)

SnapshotNode returns the index of the snapshot node paired with a node of the mapped document, and false when there is none.

func (*FactsMap) Style

func (m *FactsMap) Style(n onehtml.Node, property string) string

Style returns the computed style value the browser recorded for the node's box ("" when the node has no box or the property was not captured; a property is captured only if it was named when the facts were parsed).

func (*FactsMap) TextLines

func (m *FactsMap) TextLines(n onehtml.Node) int

TextLines returns how many lines the browser broke a text node's text into: the number of distinct vertical positions of its text boxes. It is 0 for a text node with no layout or no boxes.

func (*FactsMap) Viewport

func (m *FactsMap) Viewport() (width, height float64)

Viewport returns the viewport size the facts were taken at: the one given to WithViewport, else the snapshot's content size.

func (*FactsMap) WithBackgroundSamples

func (m *FactsMap) WithBackgroundSamples(bs *BackgroundSamples) (out *FactsMap, applied, unmatched int, err error)

WithBackgroundSamples returns a copy of the map with the samples attached to the nodes they name, and how many samples found their node and how many did not. A later sample for the same node replaces an earlier one. Samples taken in another viewport than the capture's are refused with a *FactsError of Kind "refused" and Reason "viewport-mismatch".

type FactsOption

type FactsOption func(*FactsLimits)

FactsOption configures ParseFacts.

func WithFactsLimits

func WithFactsLimits(l FactsLimits) FactsOption

WithFactsLimits sets the limits; fields left zero keep their defaults.

type Focus

type Focus struct {
	// TabIndex is the parsed tabindex attribute; without one, 0 for an
	// element that is focusable by its markup and -1 otherwise.
	TabIndex int
	// Focusable is true when the element can take focus: focusable by markup
	// (HTML section 6.6.3), rendered, not visibility hidden, not inert and
	// not disabled. aria-hidden does not prevent focus.
	Focusable bool
	// Tabbable is true when Sequential focus reaches it: focusable with a
	// non-negative TabIndex.
	Tabbable bool
	// SequentialIndex is the position in [AXTree.FocusOrder], or -1.
	SequentialIndex int
}

Focus describes how an element takes part in sequential keyboard focus.

type FormFieldEntry

type FormFieldEntry struct {
	Node     Node
	Role     string
	Label    string
	Required bool
	Invalid  bool
	Disabled bool
	// Value is the value text; empty when there is none.
	Value string
}

FormFieldEntry is a form field in NavigationLists: a text field, search field, combo box, list box, check box, radio button, switch, slider or spin button. Buttons are not listed.

type HeadingEntry

type HeadingEntry struct {
	Node Node
	// Level is the heading level, 2 when a role=heading has none.
	Level int
	Name  string
	// Lang is the declared language of the heading; HasLang is false when
	// none is declared.
	Lang    string
	HasLang bool
}

HeadingEntry is a heading in NavigationLists.

type Hidden

type Hidden struct {
	// Reasons holds, in this order, "display-none" (display none, the hidden
	// attribute, a template, a closed details), "aria-hidden", "inert" and
	// "visibility-hidden" (hidden or collapse), for those that apply.
	Reasons []string
	// Origin is the nearest element, the element itself included, that
	// causes the first reason; the zero Node when nothing hides the element.
	Origin onehtml.Node
	// Inherited is true when Origin is an ancestor.
	Inherited bool
}

Hidden says why an element is hidden from the tree's point of view.

type ImplicitProperty

type ImplicitProperty struct{ Name, Value string }

ImplicitProperty is an ARIA state or property that an element's native markup states (HTML-AAM section 3.6), such as aria-required for an input with the required attribute.

type LandmarkEntry

type LandmarkEntry struct {
	Node Node
	Role string
	Name string
	// Depth is the number of listed landmarks that contain this one.
	Depth int
}

LandmarkEntry is a landmark in NavigationLists.

type LinkEntry

type LinkEntry struct {
	Node Node
	Name string
	// Href is the href attribute as written; HasHref is false when there is
	// none.
	Href    string
	HasHref bool
	// SamePage is true when the href starts with "#".
	SamePage bool
	// URL is the href resolved by the URL Standard against the base URL
	// ([WithBaseURL], then the first base element); empty when there is no
	// href or it does not resolve.
	URL string
}

LinkEntry is a link in NavigationLists.

type MapOption

type MapOption func(*mapConfig)

MapOption configures Facts.Map.

func WithAttributeCheck

func WithAttributeCheck(c AttrCheck) MapOption

WithAttributeCheck sets how attributes are compared (default AttrValues).

func WithDocumentIndex

func WithDocumentIndex(i int) MapOption

WithDocumentIndex maps the snapshot's document of that index instead of the first (the page's).

func WithViewport

func WithViewport(width, height float64) MapOption

WithViewport states the viewport the capture was taken in, in CSS pixels. Background samples taken in another viewport are refused. Without it the document's content size stands in.

type NavigationLists struct {
	Headings   []HeadingEntry
	Landmarks  []LandmarkEntry
	Links      []LinkEntry
	FormFields []FormFieldEntry
	Tables     []TableEntry
}

NavigationLists are the lists a reader offers for jumping around a page: headings, landmarks, links, form fields and tables, each in tree order. Ignored nodes are not listed. It is plain data, safe to read from many goroutines once built.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is a handle on one node of an AXTree. The zero Node is invalid.

func (Node) Autofocus

func (n Node) Autofocus() bool

Autofocus reports whether the node's element has the autofocus attribute (HTML section 6.6.4).

func (Node) Children

func (n Node) Children() iter.Seq[Node]

Children iterates the children in tree order, ignored ones included.

func (Node) ChromeRole

func (n Node) ChromeRole() string

ChromeRole returns the role as Chrome reports it, including its internal roles (LabelText, LayoutTable, ListMarker, ...); equal to Node.Role when Chrome has no other name.

func (Node) DOM

func (n Node) DOM() onehtml.Node

DOM returns the DOM node the tree node stands for: the element, the text node, or the document. It is the zero node for a generated node (a list marker or a drop-down's popup), which has no DOM node of its own.

func (Node) Depth

func (n Node) Depth() int

Depth returns the nesting depth of the node; the document is 0.

func (Node) Description

func (n Node) Description() string

Description returns the accessible description.

func (Node) Diagnostics

func (n Node) Diagnostics() []Diagnostic

Diagnostics lists the diagnostics that concern the node's element.

func (Node) Exposed

func (n Node) Exposed() iter.Seq[Node]

Exposed iterates the children as assistive technology sees them: an ignored child is replaced by its own exposed children.

func (Node) Focus

func (n Node) Focus() Focus

Focus reports the keyboard focus facts of the node's element. Nodes of other kinds answer with the zero value and a SequentialIndex of -1.

func (Node) Ignored

func (n Node) Ignored() bool

Ignored reports whether the node is not exposed to assistive technology.

func (Node) IgnoredReasons

func (n Node) IgnoredReasons() []string

IgnoredReasons lists why a node is ignored, strongest first, using Chrome's names (ariaHiddenElement, presentationalRole, uninteresting, ...).

func (Node) Index

func (n Node) Index() int

Index is the node's position in tree order, or -1 for the zero Node.

func (Node) IsGenerated

func (n Node) IsGenerated() bool

IsGenerated reports whether the browser made the node up from layout.

func (Node) IsText

func (n Node) IsText() bool

IsText reports whether the node is static text.

func (Node) Labels

func (n Node) Labels() iter.Seq[onehtml.Node]

Labels iterates the label elements of a labelable form control, in document order: those that name it through for or by containing it (HTML section 4.10.4). Other nodes have none.

func (Node) Locator

func (n Node) Locator() (string, bool)

Locator returns the selector that names the node's element durably, the one onehtml.LocatorIndex.Locator gives for it in the tree's document. It reports false for nodes without an element (the document, text, generated nodes) and for elements that have no locator. The index of the document is built on the first call.

func (Node) Name

func (n Node) Name() string

Name returns the accessible name, white space collapsed.

func (Node) Parent

func (n Node) Parent() Node

Parent returns the parent node, or the zero Node for the document.

func (Node) Position

func (n Node) Position() (pos, size int, ok bool)

Position returns the position in set and the set size of a list item, tab, option, radio button, menu item or tree item. ok is false for other nodes.

func (Node) Properties

func (n Node) Properties() []Property

Properties returns the states and properties the node states, under Chrome's names, in a fixed order.

func (Node) Property

func (n Node) Property(name string) (Property, bool)

Property returns one property by name.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<input id=c type=checkbox checked required>`))
	tree, _ := accessibility.Tree(doc)
	box, _ := doc.SelectFirst("#c")
	ax, _ := tree.NodeFor(box)
	checked, _ := ax.Property("checked")
	fmt.Println(ax.Role(), checked)
}
Output:
checkbox true

func (Node) Relations

func (n Node) Relations() []Relation

Relations lists the relations the node's element states, in the order labelledby, describedby, controls, details, errormessage, flowto, activedescendant, owns. The list attribute of an input counts as controls. For owns only the elements the tree adopted are targets (an element another one already owns, or one that would form a cycle, is left out). The number of IDs read per attribute is bounded by WithMaxIDReferences.

Example

The relations of an element name other elements by ID; an ID that names nothing is listed as broken.

package main

import (
	"fmt"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

func main() {
	doc, _ := onehtml.ParseBytes([]byte(`<input id=a aria-describedby="hint nope"><p id=hint>Six digits</p>`))
	tree, _ := accessibility.Tree(doc)
	input := doc.Root().Descendants()
	for n := range input {
		if n.Is("input") {
			ax, _ := tree.NodeFor(n)
			for _, r := range ax.Relations() {
				for _, target := range r.Targets {
					fmt.Println(r.Kind, "->", target.Name(), target.TextContent())
				}
				fmt.Println("broken:", r.Broken)
			}
		}
	}
}
Output:
describedby -> p Six digits
broken: [nope]

func (Node) Role

func (n Node) Role() string

Role returns the Core-AAM computed role: "button", "generic", "none", "StaticText" for text, "RootWebArea" for the document. A node of an element with no role of its own has the empty role unless it is ignored, when it is "none".

func (Node) RoleOrigin

func (n Node) RoleOrigin() RoleOrigin

RoleOrigin says how the node's element got its role. It is empty for text, generated nodes and the document.

func (Node) Valid

func (n Node) Valid() bool

Valid reports whether the handle refers to a node. Every other method of the zero Node is safe and answers with an empty value.

func (Node) Value

func (n Node) Value() (string, bool)

Value returns the widget value (the text of a text field, the value of a range, the selected option of a combo box) and whether the node has one.

type NodeChange

type NodeChange struct {
	Old, New   Node
	Properties []PropertyChange
}

A NodeChange is a node present in both trees whose properties differ.

type NodeFacts

type NodeFacts struct {
	// HasLayout is true when the node has a layout box.
	HasLayout bool
	// BorderBox is x, y, width and height in CSS pixels (zero without a box).
	BorderBox [4]float64
	// ClientRect and ScrollRect are the browser's client and scroll
	// rectangles (x, y, width, height); zero when it recorded none. A box
	// whose scroll rectangle is larger than its client rectangle overflows.
	ClientRect, ScrollRect [4]float64
	// Clickable is the browser's isClickable mark.
	Clickable bool
	// Background holds the colour samples attached with
	// [FactsMap.WithBackgroundSamples]; nil without.
	Background *Background
}

NodeFacts is what the snapshot says about one node of the document.

type Option

type Option func(*config)

Option configures Tree.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sets the URL relative links and image sources resolve against for the url property.

func WithFacts

func WithFacts(f *Facts) Option

WithFacts supplies the layout facts of a browser capture of this document. With facts the tree applies the choices a browser makes once layout is known: which generic containers are left out, layout tables, list markers and layout-dependent hiding.

func WithMaxIDReferences

func WithMaxIDReferences(n int) Option

WithMaxIDReferences bounds how many ID references of one attribute (aria-labelledby, aria-describedby, aria-owns and the relations) are read; later ones are ignored and AXTree.LimitReached reports it. The default is 4096.

func WithMaxNameLength

func WithMaxNameLength(n int) Option

WithMaxNameLength cuts every accessible name and description to n UTF-16 code units (default 1,048,576) and reports the cut through AXTree.LimitReached. A value of zero or less leaves names empty.

func WithMaxNameWork

func WithMaxNameWork(n int) Option

WithMaxNameWork bounds the node visits all name computations of one tree may make together (default 4 million). A name that reaches the bound is cut short and AXTree.LimitReached reports it. A bound of zero or less cuts every name short.

func WithMaxOwnsWork

func WithMaxOwnsWork(n int) Option

WithMaxOwnsWork bounds the steps the aria-owns pass may take in all (the default is 16 million); beyond it no further aria-owns is honoured and AXTree.LimitReached reports it.

func WithStyleContext

func WithStyleContext(ctx onehtml.StyleContext) Option

WithStyleContext sets the style context the default cascade is computed under (for example the focused element). It is ignored when WithStyles is given.

func WithStyles

func WithStyles(s *onehtml.Styles) Option

WithStyles supplies the cascade to read display, visibility, generated content and the like. The default is the document's cascade under the default style context.

type PropKind

type PropKind uint8

PropKind is the type of a property value.

const (
	PropBool PropKind = iota
	PropInt
	PropNumber
	PropString
)

Property value kinds.

type Property

type Property struct {
	Name string
	Kind PropKind
	Bool bool
	Num  float64
	Str  string
}

Property is one state or property of a node: Chrome's name and a typed value. Tristate and token values are strings ("true", "false", "mixed", "horizontal").

func (Property) String

func (p Property) String() string

String formats the value: true or false for booleans, the number for numeric properties, the text otherwise.

type PropertyChange

type PropertyChange struct {
	Name     string
	Old, New string
	// HadOld and HasNew say whether the node stated the property before and
	// after; a property in only one tree has the empty value in the other.
	HadOld, HasNew bool
}

A PropertyChange is one property that differs between two trees. The properties are role, name, description, ignored, hidden (the reasons a node is ignored, comma-separated), and each state or property by the name Node.Properties gives it, with values as Property.String prints them.

type ReadingChange

type ReadingChange struct{ Before, After ReadingItem }

A ReadingChange is a reading step present in both views whose wording or language differs.

type ReadingItem

type ReadingItem struct {
	Kind ReadingKind
	// Text is the wording, never empty.
	Text string
	// Depth is the number of containers open around the step.
	Depth int
	// Lang is the value of the nearest lang attribute on the step's node or an
	// ancestor, trimmed; HasLang is false when none is declared or the nearest
	// is empty.
	Lang    string
	HasLang bool
	// Node is the tree node the step is about (the first one of a text run).
	Node Node
}

ReadingItem is one step of the reading view.

type ReadingKind

type ReadingKind uint8

ReadingKind says what a ReadingItem is.

const (
	// ReadingText is a run of text.
	ReadingText ReadingKind = iota
	// ReadingElement is an announced element that has no contents of its own
	// to walk: a link, a button, a heading.
	ReadingElement
	// ReadingStart opens a container (a list, a table, a landmark).
	ReadingStart
	// ReadingEnd closes it.
	ReadingEnd
)

The kinds of reading step.

type ReadingView

type ReadingView struct {
	// contains filtered or unexported fields
}

ReadingView is the page as one linear sequence of spoken-style steps, in generic English: what a person using a screen reader walks through. It is an approximation, not what any screen reader says; the wording is fixed so that every run gives the same steps. A ReadingView is immutable and safe for concurrent use; the zero ReadingView and a nil *ReadingView have no steps.

func (*ReadingView) Diff

Diff compares the receiver with a later reading view. A step is identified by its tree node and kind (a text run by its first text node); matched steps are changed when their wording or language differs, and a step that only moved is not a change. cs is the change set between the two snapshots, as for AXTree.Diff, and may be nil.

func (*ReadingView) Items

func (r *ReadingView) Items() iter.Seq[ReadingItem]

Items iterates the steps in reading order.

func (*ReadingView) Len

func (r *ReadingView) Len() int

Len returns the number of steps.

func (*ReadingView) String

func (r *ReadingView) String() string

String prints one step per line: two spaces of indent per depth, then "T ", "E ", "> " or "< " for text, element, start and end, then the wording, then " [lang]" when the language is known. Lines are separated by newlines, with none at the end.

func (*ReadingView) Text

func (r *ReadingView) Text() string

Text renders the wording of the steps for reading aloud or printing: one step per line, indented two spaces per depth, each line ended by a newline. Unlike ReadingView.String it has no kind marks and no language. The zero ReadingView gives the empty string.

type ReadingViewDiff

type ReadingViewDiff struct {
	// Added are the later view's unmatched steps, Removed the earlier view's.
	Added, Removed []ReadingItem
	// Changed are matched steps whose Text, Lang or HasLang differ.
	Changed []ReadingChange
}

A ReadingViewDiff is the difference between two reading views.

func (*ReadingViewDiff) IsEmpty

func (d *ReadingViewDiff) IsEmpty() bool

IsEmpty reports whether the views do not differ.

type Relation

type Relation struct {
	// Kind is one of "labelledby", "describedby", "controls", "details",
	// "errormessage", "flowto", "activedescendant" and "owns".
	Kind string
	// Targets are the elements the IDs name, in attribute order, each once.
	// An ID names the first element of the document that carries it, whether
	// or not that element has a node in the tree.
	Targets []onehtml.Node
	// Broken are the IDs that name no element, in attribute order.
	Broken []string
}

Relation is one kind of ID-reference relation of an element.

type RoleDiagnostic

type RoleDiagnostic struct {
	// Kind is one of "invalid-role-token", "abstract-role",
	// "prohibited-attribute", "unsupported-attribute", "deprecated-attribute",
	// "unknown-attribute", "invalid-attribute-value", "broken-id-reference",
	// "missing-required-attribute" and "limit-exceeded".
	Kind string
	// Attribute is the attribute the finding is about ("role" for role
	// tokens); empty for "limit-exceeded".
	Attribute string
}

RoleDiagnostic is one finding of the role layer about an element's role or ARIA attributes.

type RoleOption

type RoleOption func(*roleConfig)

RoleOption configures AXTree.ElementRole.

func WithHasAccessibleName

func WithHasAccessibleName(has bool) RoleOption

WithHasAccessibleName decides the roles that exist only for a named element (section, form, region) as if the element had or lacked a name, instead of asking the tree.

func WithMaxRoleDiagnostics

func WithMaxRoleDiagnostics(n int) RoleOption

WithMaxRoleDiagnostics bounds the diagnostics of one element (default 64); the last is then "limit-exceeded".

func WithMaxRoleIDReferences

func WithMaxRoleIDReferences(n int) RoleOption

WithMaxRoleIDReferences bounds how many IDs of one attribute are looked up (default 4096).

func WithMaxRoleTokens

func WithMaxRoleTokens(n int) RoleOption

WithMaxRoleTokens bounds how many tokens of the role attribute are read (default 64); one more is a "limit-exceeded" diagnostic.

type RoleOrigin

type RoleOrigin string

RoleOrigin says how an element's role was decided.

const (
	// RoleImplicit: the role comes from the element's markup alone (an
	// unknown or abstract role token falls back to this).
	RoleImplicit RoleOrigin = "implicit"
	// RoleExplicit: a valid token of the role attribute chose the role.
	RoleExplicit RoleOrigin = "explicit"
	// RoleConflictResolved: the role attribute said none or presentation, but
	// the element is focusable or states a global ARIA attribute, so the
	// native role stays (WAI-ARIA 1.2 section 8.4).
	RoleConflictResolved RoleOrigin = "conflict-resolved"
	// RoleInheritedPresentational: the element is a list item or table part
	// inside a presentational list or table and is presentational with it.
	RoleInheritedPresentational RoleOrigin = "inherited-presentational"
)

Role origins.

const RoleChildrenPresentational RoleOrigin = "children-presentational"

RoleChildrenPresentational: the element is inside a role whose children are presentational (a button's contents, say) and keeps no role of its own.

type RoleReport

type RoleReport struct {
	// Role is the computed role. A native img is "image", as WAI-ARIA's
	// Graphics module spells the role; children of a role whose children are
	// presentational are "none".
	Role string
	// Origin says how the role was reached; [RoleChildrenPresentational] is
	// reported here and not by [Node.RoleOrigin].
	Origin RoleOrigin
	// Explicit is the first valid, non-abstract token of the role attribute,
	// and Implicit the role the element's markup alone gives it.
	Explicit, Implicit string
	// RoleWhenNamed is the role the element would have with an accessible
	// name, when that differs from Role (a section is a region only when it
	// has one).
	RoleWhenNamed string
	// Presentational is true when Role is "none".
	Presentational bool
	// Focusable, Disabled and Inert are the element's state by markup and
	// style: see [Focus]; a disabled attribute or aria-disabled; and an inert
	// ancestor-or-self.
	Focusable, Disabled, Inert bool
	Diagnostics                []RoleDiagnostic
	ImplicitProperties         []ImplicitProperty
}

RoleReport is the role layer's account of one element.

type TableEntry

type TableEntry struct {
	Node             Node
	Caption          string
	Rows, Columns    int
	ColumnHeaderName []string
	RowHeaderName    []string
}

TableEntry is a table, grid or tree grid in NavigationLists. A table whose role is none (a presentational table) is not listed.

type TreeDiff

type TreeDiff struct {
	// Added are the later tree's unmatched nodes and Removed the earlier
	// tree's, in tree order, every node of an added or removed subtree.
	Added, Removed []Node
	// Changed are the matched nodes whose properties differ, in the later
	// tree's order.
	Changed []NodeChange
}

A TreeDiff is the difference between two trees of one document lineage.

func (*TreeDiff) IsEmpty

func (d *TreeDiff) IsEmpty() bool

IsEmpty reports whether the trees do not differ.

type UpdateInfo

type UpdateInfo struct {
	// Incremental is true when the tree was updated in place, reusing the
	// previous tree's work. The tree is always equal to a fresh build of the
	// new document; this only says how it was reached.
	Incremental bool
	// Reason says why the tree was built afresh. It is empty for a tree
	// that was not made by an update, or that was updated incrementally.
	Reason string
}

UpdateInfo says how a tree made by AXTree.Update or AXTree.WithContext came about.

Directories

Path Synopsis
Package aria is the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), the Digital Publishing module 1.1 and the Graphics module 1.0, with the characteristics the specifications give them: where a role sits in the role hierarchy, which attributes it requires, supports, deprecates or prohibits, where its accessible name may come from, and what values an attribute accepts.
Package aria is the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), the Digital Publishing module 1.1 and the Graphics module 1.0, with the characteristics the specifications give them: where a role sits in the role hierarchy, which attributes it requires, supports, deprecates or prohibits, where its accessible name may come from, and what values an attribute accepts.
Package validation checks a document against the accessibility rules of every WCAG version and level, plus best practices, and reports labelled results that point at elements.
Package validation checks a document against the accessibility rules of every WCAG version and level, plus best practices, and reports labelled results that point at elements.
gen command
Command gen writes catalogue_gen.go: the WCAG success criteria, the W3C list of ACT rules and the published table of axe-core rules, from the JSON files next to it (see SOURCE.md).
Command gen writes catalogue_gen.go: the WCAG success criteria, the W3C list of ACT rules and the published table of axe-core rules, from the JSON files next to it (see SOURCE.md).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL