[web] make text more crawlable; fix a JAWS bug (flutter/engine#50794)

On Windows, where JAWS is a popular screen reader and, [unfortunately](https://github.com/FreedomScientific/standards-support/issues/759), ignores `aria-label` on empty elements, and for user agents that are known web crawlers (that also ignore `aria-label`), render semantic text into the DOM using an additional `<span>` element.

Fixes https://github.com/flutter/flutter/issues/122607
This commit is contained in:
Yegor
2024-03-13 16:03:00 -07:00
committed by GitHub
parent 2520e4615c
commit 826074672d
13 changed files with 332 additions and 49 deletions

View File

@@ -28,6 +28,19 @@ enum BrowserEngine {
firefox,
}
/// The signature of [getUserAgent].
typedef UserAgentGetter = String Function();
/// Returns the current user agent string.
///
/// This function is read-writable, so it can be overridden in tests.
UserAgentGetter getUserAgent = defaultGetUserAgent;
/// The default implementation of [getUserAgent].
String defaultGetUserAgent() {
return domWindow.navigator.userAgent;
}
/// html webgl version qualifier constants.
abstract class WebGLVersion {
/// WebGL 1.0 is based on OpenGL ES 2.0 / GLSL 1.00
@@ -133,11 +146,10 @@ OperatingSystem? debugOperatingSystemOverride;
@visibleForTesting
OperatingSystem detectOperatingSystem({
String? overridePlatform,
String? overrideUserAgent,
int? overrideMaxTouchPoints,
}) {
final String platform = overridePlatform ?? domWindow.navigator.platform!;
final String userAgent = overrideUserAgent ?? domWindow.navigator.userAgent;
final String userAgent = getUserAgent();
if (platform.startsWith('Mac')) {
// iDevices requesting a "desktop site" spoof their UA so it looks like a Mac.

View File

@@ -13,6 +13,7 @@
import 'package:ui/ui.dart' as ui;
import 'label_and_value.dart';
import 'semantics.dart';
/// The specific type of checkable control.
@@ -51,7 +52,11 @@ _CheckableKind _checkableKindFromSemanticsFlag(
class Checkable extends PrimaryRoleManager {
Checkable(SemanticsObject semanticsObject)
: _kind = _checkableKindFromSemanticsFlag(semanticsObject),
super.withBasics(PrimaryRole.checkable, semanticsObject);
super.withBasics(
PrimaryRole.checkable,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.ariaLabel,
);
final _CheckableKind _kind;

View File

@@ -7,6 +7,7 @@ import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../platform_dispatcher.dart';
import 'focusable.dart';
import 'label_and_value.dart';
import 'semantics.dart';
/// Adds increment/decrement event handling to a semantics object.
@@ -27,7 +28,7 @@ class Incrementable extends PrimaryRoleManager {
// the one being focused on, but the internal `<input>` element.
addLiveRegion();
addRouteName();
addLabelAndValue();
addLabelAndValue(labelRepresentation: LeafLabelRepresentation.ariaLabel);
append(_element);
_element.type = 'range';

View File

@@ -2,34 +2,75 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../dom.dart';
import 'semantics.dart';
/// The method used to represend a label of a leaf node in the DOM.
///
/// This is required by some screen readers and web crawlers.
///
/// Container nodes only use `aria-label`, even if [domText] is chosen. This is
/// because screen readers treat container nodes as "groups" of other nodes, and
/// respect the `aria-label` without a [DomText] node. Crawlers typically do not
/// need this information, as they primarily scan visible text, which is
/// communicated in semantics as leaf text and heading nodes.
enum LeafLabelRepresentation {
/// Represents the label as an `aria-label` attribute.
ariaLabel,
/// Represents the label as a [DomText] node.
domText,
}
/// Renders [SemanticsObject.label] and/or [SemanticsObject.value] to the semantics DOM.
///
/// VoiceOver supports "aria-label" but only in conjunction with an ARIA role.
/// Setting "aria-label" on an empty element without a role causes VoiceOver to
/// treat element as if it does not exist. VoiceOver supports role "text", which
/// is a proprietary role not supported by other browsers. Flutter Web still
/// uses it because it provides the best user experience for plain text nodes.
///
/// TalkBack supports standalone "aria-label" attribute, but does not support
/// role "text". This leads to TalkBack reading "group" or "empty group" on
/// plain text elements, but that's still better than other alternatives
/// considered.
///
/// The value is not always rendered. Some semantics nodes correspond to
/// interactive controls, such as an `<input>` element. In such case the value
/// is reported via that element's `value` attribute rather than rendering it
/// separately.
///
/// This role manager does not manage images and text fields. See
/// [ImageRoleManager] and [TextField].
/// interactive controls. In such case the value is reported via that element's
/// `value` attribute rather than rendering it separately.
class LabelAndValue extends RoleManager {
LabelAndValue(SemanticsObject semanticsObject, PrimaryRoleManager owner)
LabelAndValue(SemanticsObject semanticsObject, PrimaryRoleManager owner, { required this.labelRepresentation })
: super(Role.labelAndValue, semanticsObject, owner);
/// Configures the representation of the label in the DOM.
final LeafLabelRepresentation labelRepresentation;
@override
void update() {
final String? computedLabel = _computeLabel();
if (computedLabel == null) {
_oldLabel = null;
_cleanUpDom();
return;
}
_updateLabel(computedLabel);
}
DomText? _domText;
String? _oldLabel;
void _updateLabel(String label) {
if (label == _oldLabel) {
return;
}
_oldLabel = label;
final bool needsDomText = labelRepresentation == LeafLabelRepresentation.domText && !semanticsObject.hasChildren;
_domText?.remove();
if (needsDomText) {
owner.removeAttribute('aria-label');
final DomText domText = domDocument.createTextNode(label);
_domText = domText;
semanticsObject.element.appendChild(domText);
} else {
owner.setAttribute('aria-label', label);
_domText = null;
}
}
String? _computeLabel() {
final bool hasValue = semanticsObject.hasValue;
final bool hasLabel = semanticsObject.hasLabel;
final bool hasTooltip = semanticsObject.hasTooltip;
@@ -39,8 +80,7 @@ class LabelAndValue extends RoleManager {
final bool shouldDisplayValue = hasValue && !semanticsObject.isIncrementable;
if (!hasLabel && !shouldDisplayValue && !hasTooltip) {
_cleanUpDom();
return;
return null;
}
final StringBuffer combinedValue = StringBuffer();
@@ -61,11 +101,12 @@ class LabelAndValue extends RoleManager {
combinedValue.write(semanticsObject.value);
}
owner.setAttribute('aria-label', combinedValue.toString());
return combinedValue.toString();
}
void _cleanUpDom() {
owner.removeAttribute('aria-label');
_domText?.remove();
}
@override

View File

@@ -7,7 +7,11 @@ import '../semantics.dart';
/// Provides accessibility for links.
class Link extends PrimaryRoleManager {
Link(SemanticsObject semanticsObject) : super.withBasics(PrimaryRole.link, semanticsObject);
Link(SemanticsObject semanticsObject) : super.withBasics(
PrimaryRole.link,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.domText,
);
@override
DomElement createElement() {

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import '../platform_views/slots.dart';
import 'label_and_value.dart';
import 'semantics.dart';
/// Manages the semantic element corresponding to a platform view.
@@ -21,7 +22,11 @@ import 'semantics.dart';
/// * https://bugs.webkit.org/show_bug.cgi?id=223798
class PlatformViewRoleManager extends PrimaryRoleManager {
PlatformViewRoleManager(SemanticsObject semanticsObject)
: super.withBasics(PrimaryRole.platformView, semanticsObject);
: super.withBasics(
PrimaryRole.platformView,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.ariaLabel,
);
@override
void update() {

View File

@@ -24,7 +24,11 @@ import 'package:ui/ui.dart' as ui;
/// viewport "scrollTop" may take positive values.
class Scrollable extends PrimaryRoleManager {
Scrollable(SemanticsObject semanticsObject)
: super.withBasics(PrimaryRole.scrollable, semanticsObject) {
: super.withBasics(
PrimaryRole.scrollable,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.ariaLabel,
) {
_scrollOverflowElement.style
..position = 'absolute'
..transformOrigin = '0 0 0'

View File

@@ -430,12 +430,15 @@ enum Role {
abstract class PrimaryRoleManager {
/// Initializes a role for a [semanticsObject] that includes basic
/// functionality for focus, labels, live regions, and route names.
PrimaryRoleManager.withBasics(this.role, this.semanticsObject) {
///
/// If `labelRepresentation` is true, configures the [LabelAndValue] role with
/// [LabelAndValue.labelRepresentation] set to true.
PrimaryRoleManager.withBasics(this.role, this.semanticsObject, { required LeafLabelRepresentation labelRepresentation }) {
element = _initElement(createElement(), semanticsObject);
addFocusManagement();
addLiveRegion();
addRouteName();
addLabelAndValue();
addLabelAndValue(labelRepresentation: labelRepresentation);
addTappable();
}
@@ -539,8 +542,8 @@ abstract class PrimaryRoleManager {
}
/// Adds generic label features.
void addLabelAndValue() {
addSecondaryRole(LabelAndValue(semanticsObject, this));
void addLabelAndValue({ required LeafLabelRepresentation labelRepresentation }) {
addSecondaryRole(LabelAndValue(semanticsObject, this, labelRepresentation: labelRepresentation));
}
/// Adds generic functionality for handling taps and clicks.
@@ -618,7 +621,11 @@ abstract class PrimaryRoleManager {
/// A role used when a more specific role couldn't be assigned to the node.
final class GenericRole extends PrimaryRoleManager {
GenericRole(SemanticsObject semanticsObject) : super.withBasics(PrimaryRole.generic, semanticsObject);
GenericRole(SemanticsObject semanticsObject) : super.withBasics(
PrimaryRole.generic,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.domText,
);
@override
void update() {

View File

@@ -7,7 +7,11 @@ import 'package:ui/ui.dart' as ui;
/// Sets the "button" ARIA role.
class Button extends PrimaryRoleManager {
Button(SemanticsObject semanticsObject) : super.withBasics(PrimaryRole.button, semanticsObject) {
Button(SemanticsObject semanticsObject) : super.withBasics(
PrimaryRole.button,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.domText,
) {
setAriaRole('button');
}

View File

@@ -49,13 +49,18 @@ void testMain() {
String ua = 'any',
int touchPoints = 0,
}) {
expect(
try {
getUserAgent = () => ua;
expect(
detectOperatingSystem(
overridePlatform: platform,
overrideUserAgent: ua,
overrideMaxTouchPoints: touchPoints,
),
expectedOs);
expectedOs,
);
} finally {
getUserAgent = defaultGetUserAgent;
}
}
test('Determine unknown for weird values of platform/ua', () {

View File

@@ -77,6 +77,7 @@ void testMain() {
expect(pluginsRegistered, isTrue, reason: 'Plugins should be immediately registered in autoStart mode.');
expect(appRan, isTrue, reason: 'App should run immediately in autoStart mode');
});
// We cannot test anymore, because by now the engine has registered some stuff that can't be rewound back.
// Like the `ext.flutter.disassemble` developer extension.
}

View File

@@ -0,0 +1,194 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../../common/rendering.dart';
import '../../common/test_initialization.dart';
import 'semantics_tester.dart';
const String _rootStyle = 'style="filter: opacity(0%); color: rgba(0, 0, 0, 0)"';
DateTime _testTime = DateTime(2023, 2, 17);
EngineSemantics semantics() => EngineSemantics.instance;
EngineSemanticsOwner owner() => EnginePlatformDispatcher.instance.implicitView!.semantics;
void main() {
internalBootstrapBrowserTest(() {
return testMain;
});
}
Future<void> testMain() async {
await bootstrapAndRunApp(withImplicitView: true);
setUpRenderingForTests();
test('renders label text as DOM', () async {
semantics()
..debugOverrideTimestampFunction(() => _testTime)
..semanticsEnabled = true;
// Add a node with a label - expect a <span>
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'Hello',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem role="text" $_rootStyle>Hello</sem>'''
);
final SemanticsObject node = owner().debugSemanticsTree![0]!;
expect(node.primaryRole?.role, PrimaryRole.generic);
expect(
reason: 'A node with a label should get a LabelAndValue role',
node.primaryRole!.debugSecondaryRoles,
contains(Role.labelAndValue),
);
}
// Change label - expect both <span> and aria-label to be updated.
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'World',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem role="text" $_rootStyle>World</sem>'''
);
}
// Empty the label - expect the <span> to be removed.
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: '',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
);
tester.apply();
expectSemanticsTree(owner(), '<sem role="text" $_rootStyle></sem>');
}
semantics().semanticsEnabled = false;
});
test('does not add a span in container nodes', () async {
semantics()
..debugOverrideTimestampFunction(() => _testTime)
..semanticsEnabled = true;
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'I am a parent',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
children: <SemanticsNodeUpdate>[
tester.updateNode(
id: 1,
label: 'I am a child',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
),
],
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem aria-label="I am a parent" role="group" $_rootStyle>
<sem-c>
<sem role="text">I am a child</sem>
</sem-c>
</sem>'''
);
semantics().semanticsEnabled = false;
});
test('adds a span when a leaf becomes a parent, and vice versa', () async {
semantics()
..debugOverrideTimestampFunction(() => _testTime)
..semanticsEnabled = true;
// A leaf node with a label - expect <span>
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'I am a leaf',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem role="text" $_rootStyle>I am a leaf</sem>'''
);
}
// Add a child - expect <span> to be removed from the parent.
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'I am a parent',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
children: <SemanticsNodeUpdate>[
tester.updateNode(
id: 1,
label: 'I am a child',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
),
],
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem aria-label="I am a parent" role="group" $_rootStyle>
<sem-c>
<sem role="text">I am a child</sem>
</sem-c>
</sem>'''
);
}
// Remove the child - expect the <span> to be readded to the former parent.
{
final SemanticsTester tester = SemanticsTester(owner());
tester.updateNode(
id: 0,
label: 'I am a leaf again',
transform: Matrix4.identity().toFloat64(),
rect: const ui.Rect.fromLTRB(0, 0, 100, 50),
);
tester.apply();
expectSemanticsTree(owner(), '''
<sem role="text" $_rootStyle>I am a leaf again</sem>'''
);
}
semantics().semanticsEnabled = false;
});
}

View File

@@ -140,7 +140,7 @@ void _testRoleManagerLifecycle() {
);
tester.apply();
tester.expectSemantics('<sem aria-label="a label" role="button" style="$rootSemanticStyle"></sem>');
tester.expectSemantics('<sem role="button" style="$rootSemanticStyle">a label</sem>');
final SemanticsObject node = owner().debugSemanticsTree![0]!;
expect(node.primaryRole?.role, PrimaryRole.button);
@@ -319,7 +319,7 @@ void _testEngineSemanticsOwner() {
renderSemantics(label: label);
}
test('produces an aria-label', () async {
test('produces a label', () async {
semantics().semanticsEnabled = true;
// Create
@@ -335,7 +335,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem role="text" aria-label="Hello"></sem>
<sem role="text">Hello</sem>
</sem-c>
</sem>''');
@@ -345,7 +345,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem role="text" aria-label="World"></sem>
<sem role="text">World</sem>
</sem-c>
</sem>''');
@@ -378,7 +378,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem aria-label="Hello" role="text"></sem>
<sem role="text">Hello</sem>
</sem-c>
</sem>''');
@@ -393,7 +393,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<a aria-label="Hello" style="display: block;"></a>
<a style="display: block;">Hello</a>
</sem-c>
</sem>''');
expect(existingParent, tree[1]!.element.parent);
@@ -417,7 +417,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem aria-label="tooltip"></sem>
<sem>tooltip</sem>
</sem-c>
</sem>''');
@@ -427,7 +427,7 @@ void _testEngineSemanticsOwner() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem role="text" aria-label="tooltip\nHello"></sem>
<sem role="text">tooltip\nHello</sem>
</sem-c>
</sem>''');
@@ -630,7 +630,7 @@ void _testHeader() {
owner().updateSemantics(builder.build());
expectSemanticsTree(owner(), '''
<sem role="heading" aria-label="Header of the page" style="$rootSemanticStyle"></sem>
<sem role="heading" style="$rootSemanticStyle">Header of the page</sem>
''');
semantics().semanticsEnabled = false;
@@ -2780,7 +2780,7 @@ void _testDialog() {
<sem-c>
<sem>
<sem-c>
<sem role="text" aria-label="$label"></sem>
<sem role="text">$label</sem>
</sem-c>
</sem>
</sem-c>
@@ -2869,7 +2869,7 @@ void _testDialog() {
<sem-c>
<sem>
<sem-c>
<sem role="text" aria-label="Hello"></sem>
<sem role="text">Hello</sem>
</sem-c>
</sem>
</sem-c>
@@ -3228,7 +3228,7 @@ void _testFocusable() {
expectSemanticsTree(owner(), '''
<sem style="$rootSemanticStyle">
<sem-c>
<sem role="text" aria-label="focusable text"></sem>
<sem role="text">focusable text</sem>
</sem-c>
</sem>
''');