Repository navigation
Expand file tree
/
Copy pathsemantics.dart
More file actions
7352 lines (6718 loc) · 272 KB
/
Copy pathsemantics.dart
File metadata and controls
7352 lines (6718 loc) · 272 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 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.
/// @docImport 'dart:ui';
///
/// @docImport 'package:flutter/material.dart';
/// @docImport 'package:flutter/rendering.dart';
/// @docImport 'package:flutter_test/flutter_test.dart';
library;
import 'dart:core';
import 'dart:math' as math;
import 'dart:ui'
show
CheckedState,
Locale,
Offset,
Rect,
SemanticsAction,
SemanticsFlag,
SemanticsFlags,
SemanticsInputType,
SemanticsRole,
SemanticsUpdate,
SemanticsUpdateBuilder,
SemanticsValidationResult,
StringAttribute,
TextDirection,
Tristate;
import 'dart:ui' as ui show SemanticsHitTestBehavior;
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart' show MatrixUtils, TransformProperty;
import 'package:flutter/services.dart';
import 'package:vector_math/vector_math_64.dart';
import 'binding.dart' show SemanticsBinding;
import 'semantics_event.dart';
export 'dart:ui'
show
Offset,
Rect,
SemanticsAction,
SemanticsFlag,
SemanticsFlags,
SemanticsRole,
SemanticsValidationResult,
StringAttribute,
TextDirection,
VoidCallback;
export 'package:flutter/foundation.dart'
show
DiagnosticLevel,
DiagnosticPropertiesBuilder,
DiagnosticsNode,
DiagnosticsTreeStyle,
Key,
TextTreeConfiguration;
export 'package:flutter/services.dart' show TextSelection;
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'semantics_event.dart' show SemanticsEvent;
/// Signature for a function that is called for each [SemanticsNode].
///
/// Return false to stop visiting nodes.
///
/// Used by [SemanticsNode.visitChildren].
typedef SemanticsNodeVisitor = bool Function(SemanticsNode node);
/// Signature for [SemanticsAction]s that move the cursor.
///
/// If `extendSelection` is set to true the cursor movement should extend the
/// current selection or (if nothing is currently selected) start a selection.
typedef MoveCursorHandler = void Function(bool extendSelection);
/// Signature for the [SemanticsAction.setSelection] handlers to change the
/// text selection (or re-position the cursor) to `selection`.
typedef SetSelectionHandler = void Function(TextSelection selection);
/// Signature for the [SemanticsAction.setText] handlers to replace the
/// current text with the input `text`.
typedef SetTextHandler = void Function(String text);
/// Signature for the [SemanticsAction.scrollToOffset] handlers to scroll the
/// scrollable container to the given `targetOffset`.
typedef ScrollToOffsetHandler = void Function(Offset targetOffset);
/// Signature for a handler of a [SemanticsAction].
///
/// Returned by [SemanticsConfiguration.getActionHandler].
typedef SemanticsActionHandler = void Function(Object? args);
/// Signature for a function that receives a semantics update and returns no result.
///
/// Used by [SemanticsOwner.onSemanticsUpdate].
typedef SemanticsUpdateCallback = void Function(SemanticsUpdate update);
/// Signature for the [SemanticsConfiguration.childConfigurationsDelegate].
///
/// The input list contains all [SemanticsConfiguration]s that rendering
/// children want to merge upward. One can tag a render child with a
/// [SemanticsTag] and look up its [SemanticsConfiguration]s through
/// [SemanticsConfiguration.tagsChildrenWith].
///
/// The return value is the arrangement of these configs, including which
/// configs continue to merge upward and which configs form sibling merge group.
///
/// Use [ChildSemanticsConfigurationsResultBuilder] to generate the return
/// value.
typedef ChildSemanticsConfigurationsDelegate = ChildSemanticsConfigurationsResult Function(
List<SemanticsConfiguration>,
);
/// Controls how accessibility focus is blocked.
///
/// This is typically used to prevent screen readers from focusing on parts
/// of the UI.
///
/// Setting this property also blocks the reporting of keyboard focusability
/// for the semantics node, but it does not affect the actual keyboard focus
/// handled by [FocusNode].
enum AccessibilityFocusBlockType {
/// Accessibility focus is **not blocked**.
none,
/// Blocks accessibility focus for the entire subtree.
blockSubtree,
/// Blocks accessibility focus for the **current node only**. Its descendants
/// may still be focusable.
blockNode;
/// The AccessibilityFocusBlockType when two nodes get merged.
AccessibilityFocusBlockType _merge(AccessibilityFocusBlockType other) {
// 1. If either is blockSubtree, the result is blockSubtree.
if (this == AccessibilityFocusBlockType.blockSubtree ||
other == AccessibilityFocusBlockType.blockSubtree) {
return AccessibilityFocusBlockType.blockSubtree;
}
// 2. If either is blockNode, the result is blockNode
if (this == AccessibilityFocusBlockType.blockNode ||
other == AccessibilityFocusBlockType.blockNode) {
return AccessibilityFocusBlockType.blockNode;
}
// 3. If neither is blockSubtree nor blockNode, both must be none.
return AccessibilityFocusBlockType.none;
}
}
final int _kUnblockedUserActions =
SemanticsAction.didGainAccessibilityFocus.index |
SemanticsAction.didLoseAccessibilityFocus.index;
/// A static class to conduct semantics role checks.
sealed class _DebugSemanticsRoleChecks {
static FlutterError? _checkSemanticsData(SemanticsNode node) {
final FlutterError? error = switch (node.role) {
SemanticsRole.alertDialog => _noCheckRequired,
SemanticsRole.dialog => _noCheckRequired,
SemanticsRole.none => _noCheckRequired,
SemanticsRole.tab => _semanticsTab,
SemanticsRole.tabBar => _semanticsTabBar,
SemanticsRole.tabPanel => _noCheckRequired,
SemanticsRole.table => _semanticsTable,
SemanticsRole.cell => _semanticsCell,
SemanticsRole.row => _semanticsRow,
SemanticsRole.columnHeader => _semanticsColumnHeader,
SemanticsRole.radioGroup => _semanticsRadioGroup,
SemanticsRole.menu => _semanticsMenu,
SemanticsRole.menuBar => _semanticsMenuBar,
SemanticsRole.menuItem => _semanticsMenuItem,
SemanticsRole.menuItemCheckbox => _semanticsMenuItemCheckbox,
SemanticsRole.menuItemRadio => _semanticsMenuItemRadio,
SemanticsRole.alert => _noLiveRegion,
SemanticsRole.status => _noLiveRegion,
SemanticsRole.list => _noCheckRequired,
SemanticsRole.listItem => _semanticsListItem,
SemanticsRole.complementary => _semanticsComplementary,
SemanticsRole.contentInfo => _semanticsContentInfo,
SemanticsRole.main => _semanticsMain,
SemanticsRole.navigation => _semanticsNavigation,
SemanticsRole.region => _semanticsRegion,
SemanticsRole.form => _noCheckRequired,
SemanticsRole.loadingSpinner => _noCheckRequired,
SemanticsRole.progressBar => _semanticsProgressBar,
SemanticsRole.slider => _semanticsSlider,
// TODO(chunhtai): add checks when the roles are used in framework.
// https://github.com/flutter/flutter/issues/159741.
SemanticsRole.dragHandle => _unimplemented,
SemanticsRole.spinButton => _unimplemented,
SemanticsRole.comboBox => _unimplemented,
SemanticsRole.tooltip => _unimplemented,
SemanticsRole.hotKey => _unimplemented,
}(node);
if (error != null) {
return error;
}
return _semanticsGeneral(node);
}
static FlutterError? _unimplemented(SemanticsNode node) =>
FlutterError('Missing checks for role ${node.getSemanticsData().role}');
static FlutterError? _noCheckRequired(SemanticsNode node) => null;
static FlutterError? _semanticsProgressBar(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
// Check if value is present
if (data.value.isEmpty ||
(data.minValue?.isEmpty ?? true) ||
(data.maxValue?.isEmpty ?? true)) {
return FlutterError('A progress bar must have a value, a minValue, a maxValue.');
}
final double? minVal = double.tryParse(data.minValue!);
final double? maxVal = double.tryParse(data.maxValue!);
// The value can either be a direct number fall within the min and max range
// or a percentage number between 0% and 100%
final double? currentValue = double.tryParse(data.value);
final double? percentValue = data.value.endsWith('%')
? double.tryParse(data.value.substring(0, data.value.length - 1))
: null;
if (minVal == null || maxVal == null || (currentValue == null && percentValue == null)) {
return FlutterError(
'Progress bar value, minValue, and maxValue must be valid numbers. '
'value: "${data.value}", minValue: "${data.minValue}", maxValue: "${data.maxValue}"',
);
}
// Validate min/max relation since both are guaranteed to be valid numbers.
if (minVal >= maxVal) {
return FlutterError(
'Progress bar minValue (${data.minValue}) must be less than maxValue (${data.maxValue})',
);
}
// If the value is a number, it must be between min and max.
if (currentValue != null) {
if (currentValue < minVal || currentValue > maxVal) {
return FlutterError(
'Progress bar value (${data.value}) must be between minValue (${data.minValue}) and maxValue (${data.maxValue})',
);
}
return null;
}
// If the value is a percentage string (e.g., "50%"), it must be between 0% and 100%.
if (percentValue != null && (percentValue < 0 || percentValue > 100)) {
return FlutterError(
'Progress bar percentage value (${data.value}) must be between 0% and 100%',
);
}
return null;
}
static FlutterError? _semanticsSlider(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
// Check if value is present
if (data.value.isEmpty) {
return FlutterError('A slider must have a value');
}
// Check if minValue and maxValue are present
if (data.minValue?.isEmpty ?? true) {
return FlutterError('A slider must have a minValue');
}
if (data.maxValue?.isEmpty ?? true) {
return FlutterError('A slider must have a maxValue');
}
// Validate that value is within min and max range
try {
final double currentValue = double.parse(data.value.replaceAll('%', ''));
final double minVal = double.parse(data.minValue!);
final double maxVal = double.parse(data.maxValue!);
if (minVal >= maxVal) {
return FlutterError(
'Slider minValue (${data.minValue}) must be less than maxValue (${data.maxValue})',
);
}
if (data.value.contains('%')) {
if (currentValue < 0.0 || currentValue > 100.0) {
return FlutterError(
'Slider percentage value (${data.value}) must be between 0% and 100%',
);
}
} else {
if (currentValue < minVal || currentValue > maxVal) {
return FlutterError(
'Slider value (${data.value}) must be between minValue (${data.minValue}) and maxValue (${data.maxValue})',
);
}
}
} on FormatException {
return FlutterError(
'Slider value, minValue, and maxValue must be valid numbers. '
'value: "${data.value}", minValue: "${data.minValue}", maxValue: "${data.maxValue}"',
);
}
return null;
}
static FlutterError? _semanticsTab(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.flagsCollection.isSelected == Tristate.none) {
return FlutterError('A tab needs selected states');
}
if (node.areUserActionsBlocked) {
return null;
}
if (data.flagsCollection.isEnabled != Tristate.isFalse &&
!data.hasAction(SemanticsAction.tap)) {
return FlutterError('A tab must have a tap action');
}
return null;
}
static FlutterError? _semanticsTabBar(SemanticsNode node) {
if (node.childrenCount < 1) {
return FlutterError('a TabBar cannot be empty');
}
FlutterError? error;
node.visitChildren((SemanticsNode child) {
if (child.getSemanticsData().role != SemanticsRole.tab) {
error = FlutterError('Children of TabBar must have the tab role');
}
return error == null;
});
return error;
}
static FlutterError? _semanticsTable(SemanticsNode node) {
FlutterError? error;
node.visitChildren((SemanticsNode child) {
if (child.getSemanticsData().role != SemanticsRole.row) {
error = FlutterError('Children of Table must have the row role');
}
return error == null;
});
return error;
}
static FlutterError? _semanticsRow(SemanticsNode node) {
if (node.parent?.role != SemanticsRole.table) {
return FlutterError('A row must be a child of a table');
}
FlutterError? error;
node.visitChildren((SemanticsNode child) {
if (child.getSemanticsData().role != SemanticsRole.cell &&
child.getSemanticsData().role != SemanticsRole.columnHeader) {
error = FlutterError('Children of Row must have the cell or columnHeader role');
}
return error == null;
});
return error;
}
static FlutterError? _semanticsCell(SemanticsNode node) {
if (node.parent?.role != SemanticsRole.row && node.parent?.role != SemanticsRole.cell) {
return FlutterError('A cell must be a child of a row or another cell');
}
return null;
}
static FlutterError? _semanticsColumnHeader(SemanticsNode node) {
if (node.parent?.role != SemanticsRole.row && node.parent?.role != SemanticsRole.cell) {
return FlutterError('A columnHeader must be a child or another cell');
}
return null;
}
static FlutterError? _semanticsRadioGroup(SemanticsNode node) {
FlutterError? error;
var hasCheckedChild = false;
bool validateRadioGroupChildren(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.role == SemanticsRole.radioGroup) {
// Children under sub radio groups don't belong to this radio group.
return error == null;
}
if (!data.flagsCollection.isInMutuallyExclusiveGroup) {
node.visitChildren(validateRadioGroupChildren);
return error == null;
}
if (data.flagsCollection.isChecked == CheckedState.isTrue) {
if (hasCheckedChild) {
error = FlutterError('Radio groups must not have multiple checked children');
return false;
}
hasCheckedChild = true;
}
assert(error == null);
return true;
}
node.visitChildren(validateRadioGroupChildren);
return error;
}
static FlutterError? _semanticsMenu(SemanticsNode node) {
if (node.childrenCount < 1) {
return FlutterError('a menu cannot be empty');
}
return null;
}
static FlutterError? _semanticsMenuBar(SemanticsNode node) {
if (node.childrenCount < 1) {
return FlutterError('a menu bar cannot be empty');
}
return null;
}
static FlutterError? _semanticsMenuItem(SemanticsNode node) {
SemanticsNode? currentNode = node;
while (currentNode?.parent != null) {
if (currentNode?.parent?.role == SemanticsRole.menu ||
currentNode?.parent?.role == SemanticsRole.menuBar) {
return null;
}
currentNode = currentNode?.parent;
}
return FlutterError('A menu item must be a child of a menu or a menu bar');
}
static FlutterError? _semanticsMenuItemCheckbox(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.flagsCollection.isChecked == CheckedState.none) {
return FlutterError('a menu item checkbox must be checkable');
}
SemanticsNode? currentNode = node;
while (currentNode?.parent != null) {
if (currentNode?.parent?.role == SemanticsRole.menu ||
currentNode?.parent?.role == SemanticsRole.menuBar) {
return null;
}
currentNode = currentNode?.parent;
}
return FlutterError('A menu item checkbox must be a child of a menu or a menu bar');
}
static FlutterError? _semanticsMenuItemRadio(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.flagsCollection.isChecked == CheckedState.none) {
return FlutterError('a menu item radio must be checkable');
}
SemanticsNode? currentNode = node;
while (currentNode?.parent != null) {
if (currentNode?.parent?.role == SemanticsRole.menu ||
currentNode?.parent?.role == SemanticsRole.menuBar) {
return null;
}
currentNode = currentNode?.parent;
}
return FlutterError('A menu item radio must be a child of a menu or a menu bar');
}
static FlutterError? _noLiveRegion(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.flagsCollection.isLiveRegion) {
return FlutterError(
'Node ${node.id} has role ${data.role} but is also a live region. '
'A node can not have ${data.role} and be live region at the same time. '
'Either remove the role or the live region',
);
}
return null;
}
static FlutterError? _semanticsListItem(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
final SemanticsNode? parent = node.parent;
if (parent == null) {
return FlutterError(
"Semantics node ${node.id} has role ${data.role} but doesn't have a parent",
);
}
final SemanticsData parentSemanticsData = parent.getSemanticsData();
if (parentSemanticsData.role != SemanticsRole.list) {
return FlutterError(
'Semantics node ${node.id} has role ${data.role}, but its '
"parent node ${parent.id} doesn't have the role ${SemanticsRole.list}. "
'Please assign the ${SemanticsRole.list} to node ${parent.id}',
);
}
return null;
}
static bool _isLandmarkRole(SemanticsData nodeData) =>
nodeData.role == SemanticsRole.complementary ||
nodeData.role == SemanticsRole.contentInfo ||
nodeData.role == SemanticsRole.main ||
nodeData.role == SemanticsRole.navigation ||
nodeData.role == SemanticsRole.region;
static bool _isSameRoleExisted(SemanticsNode semanticsNode) {
final Map<int, SemanticsNode> treeNodes = semanticsNode.owner!._nodes;
var sameRoleCount = 0;
for (final int id in treeNodes.keys) {
if (treeNodes[id]?.getSemanticsData().role == semanticsNode.role) {
sameRoleCount++;
if (sameRoleCount > 1) {
return true;
}
}
}
return false;
}
static FlutterError? _semanticsComplementary(SemanticsNode node) {
SemanticsNode? currentNode = node.parent;
while (currentNode != null) {
if (_isLandmarkRole(currentNode.getSemanticsData())) {
return FlutterError(
'The complementary landmark role should not contained within any other landmark roles.',
);
}
currentNode = currentNode.parent;
}
final SemanticsData data = node.getSemanticsData();
if (_isSameRoleExisted(node) && data.label.isEmpty) {
return FlutterError(
'The complementary landmark role should have a unique label as it is used more than once.',
);
}
return null;
}
static FlutterError? _semanticsContentInfo(SemanticsNode node) {
SemanticsNode? currentNode = node.parent;
while (currentNode != null) {
if (_isLandmarkRole(currentNode.getSemanticsData())) {
return FlutterError(
'The contentInfo landmark role should not contained within any other landmark roles.',
);
}
currentNode = currentNode.parent;
}
final SemanticsData data = node.getSemanticsData();
if (_isSameRoleExisted(node) && data.label.isEmpty) {
return FlutterError(
'The contentInfo landmark role should have a unique label as it is used more than once.',
);
}
return null;
}
static FlutterError? _semanticsMain(SemanticsNode node) {
SemanticsNode? currentNode = node.parent;
while (currentNode != null) {
if (_isLandmarkRole(currentNode.getSemanticsData())) {
return FlutterError(
'The main landmark role should not contained within any other landmark roles.',
);
}
currentNode = currentNode.parent;
}
final SemanticsData data = node.getSemanticsData();
if (_isSameRoleExisted(node) && data.label.isEmpty) {
return FlutterError(
'The main landmark role should have a unique label as it is used more than once.',
);
}
return null;
}
static FlutterError? _semanticsNavigation(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (_isSameRoleExisted(node) && data.label.isEmpty) {
return FlutterError(
'The navigation landmark role should have a unique label as it is used more than once.',
);
}
return null;
}
static FlutterError? _semanticsRegion(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
if (data.label.isEmpty) {
return FlutterError(
'A region role should include a label that describes the purpose of the content.',
);
}
return null;
}
static FlutterError? _semanticsGeneral(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
final bool? isExpanded = data.flagsCollection.isExpanded.toBoolOrNull();
if (isExpanded != null) {
final bool hasExpandAction = data.hasAction(SemanticsAction.expand);
final bool hasCollapseAction = data.hasAction(SemanticsAction.collapse);
if (hasExpandAction && hasCollapseAction) {
return FlutterError(
'An expandable node cannot have both expand and collapse actions set at the same time.',
);
}
if (isExpanded && hasExpandAction) {
return FlutterError('An expanded node cannot have an expand action.');
}
if (!isExpanded && hasCollapseAction) {
return FlutterError('A collapsed node cannot have a collapse action.');
}
}
if (data.flagsCollection.isAccessibilityFocusBlocked &&
data.flagsCollection.isFocused != Tristate.none) {
return FlutterError(
'A node that is keyboard focusable cannot be set to accessibility unfocusable',
);
}
return null;
}
}
/// A tag for a [SemanticsNode].
///
/// Tags can be interpreted by the parent of a [SemanticsNode]
/// and depending on the presence of a tag the parent can for example decide
/// how to add the tagged node as a child. Tags are not sent to the engine.
///
/// As an example, the [RenderSemanticsGestureHandler] uses tags to determine
/// if a child node should be excluded from the scrollable area for semantic
/// purposes.
///
/// The provided [name] is only used for debugging. Two tags created with the
/// same [name] and the `new` operator are not considered identical. However,
/// two tags created with the same [name] and the `const` operator are always
/// identical.
class SemanticsTag {
/// Creates a [SemanticsTag].
///
/// The provided [name] is only used for debugging. Two tags created with the
/// same [name] and the `new` operator are not considered identical. However,
/// two tags created with the same [name] and the `const` operator are always
/// identical.
const SemanticsTag(this.name);
/// A human-readable name for this tag used for debugging.
///
/// This string is not used to determine if two tags are identical.
final String name;
@override
String toString() => '${objectRuntimeType(this, 'SemanticsTag')}($name)';
}
/// The result that contains the arrangement for the child
/// [SemanticsConfiguration]s.
///
/// When the [PipelineOwner] builds the semantics tree, it uses the returned
/// [ChildSemanticsConfigurationsResult] from
/// [SemanticsConfiguration.childConfigurationsDelegate] to decide how semantics nodes
/// should form.
///
/// Use [ChildSemanticsConfigurationsResultBuilder] to build the result.
class ChildSemanticsConfigurationsResult {
ChildSemanticsConfigurationsResult._(this.mergeUp, this.siblingMergeGroups);
/// Returns the [SemanticsConfiguration]s that are supposed to be merged into
/// the parent semantics node.
///
/// [SemanticsConfiguration]s that are either semantics boundaries or are
/// conflicting with other [SemanticsConfiguration]s will form explicit
/// semantics nodes. All others will be merged into the parent.
final List<SemanticsConfiguration> mergeUp;
/// The groups of child semantics configurations that want to merge together
/// and form a sibling [SemanticsNode].
///
/// All the [SemanticsConfiguration]s in a given group that are either
/// semantics boundaries or are conflicting with other
/// [SemanticsConfiguration]s of the same group will be excluded from the
/// sibling merge group and form independent semantics nodes as usual.
///
/// The result [SemanticsNode]s from the merges are attached as the sibling
/// nodes of the immediate parent semantics node. For example, a `RenderObjectA`
/// has a rendering child, `RenderObjectB`. If both of them form their own
/// semantics nodes, `SemanticsNodeA` and `SemanticsNodeB`, any semantics node
/// created from sibling merge groups of `RenderObjectB` will be attach to
/// `SemanticsNodeA` as a sibling of `SemanticsNodeB`.
final List<List<SemanticsConfiguration>> siblingMergeGroups;
}
/// The builder to build a [ChildSemanticsConfigurationsResult] based on its
/// annotations.
///
/// To use this builder, one can use [markAsMergeUp] and
/// [markAsSiblingMergeGroup] to annotate the arrangement of
/// [SemanticsConfiguration]s. Once all the configs are annotated, use [build]
/// to generate the [ChildSemanticsConfigurationsResult].
class ChildSemanticsConfigurationsResultBuilder {
/// Creates a [ChildSemanticsConfigurationsResultBuilder].
ChildSemanticsConfigurationsResultBuilder();
final List<SemanticsConfiguration> _mergeUp = <SemanticsConfiguration>[];
final List<List<SemanticsConfiguration>> _siblingMergeGroups = <List<SemanticsConfiguration>>[];
/// Marks the [SemanticsConfiguration] to be merged into the parent semantics
/// node.
///
/// The [SemanticsConfiguration] will be added to the
/// [ChildSemanticsConfigurationsResult.mergeUp] that this builder builds.
void markAsMergeUp(SemanticsConfiguration config) => _mergeUp.add(config);
/// Marks a group of [SemanticsConfiguration]s to merge together
/// and form a sibling [SemanticsNode].
///
/// The group of [SemanticsConfiguration]s will be added to the
/// [ChildSemanticsConfigurationsResult.siblingMergeGroups] that this builder builds.
void markAsSiblingMergeGroup(List<SemanticsConfiguration> configs) =>
_siblingMergeGroups.add(configs);
/// Builds a [ChildSemanticsConfigurationsResult] contains the arrangement.
ChildSemanticsConfigurationsResult build() {
assert(() {
final seenConfigs = <SemanticsConfiguration>{};
for (final config in <SemanticsConfiguration>[
..._mergeUp,
..._siblingMergeGroups.flattened,
]) {
assert(
seenConfigs.add(config),
'Duplicated SemanticsConfigurations. This can happen if the same '
'SemanticsConfiguration was marked twice in markAsMergeUp and/or '
'markAsSiblingMergeGroup',
);
}
return true;
}());
return ChildSemanticsConfigurationsResult._(_mergeUp, _siblingMergeGroups);
}
}
/// An identifier of a custom semantics action.
///
/// Custom semantics actions can be provided to make complex user
/// interactions more accessible. For instance, if an application has a
/// drag-and-drop list that requires the user to press and hold an item
/// to move it, users interacting with the application using a hardware
/// switch may have difficulty. This can be made accessible by creating custom
/// actions and pairing them with handlers that move a list item up or down in
/// the list.
///
/// In Android, these actions are presented in the local context menu. In iOS,
/// these are presented in the radial context menu.
///
/// Localization and text direction do not automatically apply to the provided
/// label or hint.
///
/// Instances of this class should either be instantiated with const or
/// new instances cached in static fields.
///
/// See also:
///
/// * [SemanticsProperties], where the handler for a custom action is provided.
@immutable
class CustomSemanticsAction {
/// Creates a new [CustomSemanticsAction].
///
/// The [label] must not be empty.
const CustomSemanticsAction({required String this.label})
: assert(label != ''),
hint = null,
action = null;
/// Creates a new [CustomSemanticsAction] that overrides a standard semantics
/// action.
///
/// The [hint] must not be empty.
const CustomSemanticsAction.overridingAction({
required String this.hint,
required SemanticsAction this.action,
}) : assert(hint != ''),
label = null;
/// The user readable name of this custom semantics action.
final String? label;
/// The hint description of this custom semantics action.
final String? hint;
/// The standard semantics action this action replaces.
final SemanticsAction? action;
@override
int get hashCode => Object.hash(label, hint, action);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is CustomSemanticsAction &&
other.label == label &&
other.hint == hint &&
other.action == action;
}
@override
String toString() {
return 'CustomSemanticsAction(${_ids[this]}, label:$label, hint:$hint, action:$action)';
}
// Logic to assign a unique id to each custom action without requiring
// user specification.
static int _nextId = 0;
static final Map<int, CustomSemanticsAction> _actions = <int, CustomSemanticsAction>{};
static final Map<CustomSemanticsAction, int> _ids = <CustomSemanticsAction, int>{};
/// Get the identifier for a given `action`.
static int getIdentifier(CustomSemanticsAction action) {
int? result = _ids[action];
if (result == null) {
result = _nextId++;
_ids[action] = result;
_actions[result] = action;
}
return result;
}
/// Get the `action` for a given identifier.
static CustomSemanticsAction? getAction(int id) {
return _actions[id];
}
/// Resets internal state between tests. Does nothing if asserts are disabled.
@visibleForTesting
static void resetForTests() {
assert(() {
_actions.clear();
_ids.clear();
_nextId = 0;
return true;
}());
}
}
/// A string that carries a list of [StringAttribute]s.
@immutable
class AttributedString {
/// Creates a attributed string.
///
/// The [TextRange] in the [attributes] must be inside the length of the
/// [string].
///
/// The [attributes] must not be changed after the attributed string is
/// created.
AttributedString(this.string, {this.attributes = const <StringAttribute>[]})
: assert(string.isNotEmpty || attributes.isEmpty),
assert(() {
for (final attribute in attributes) {
assert(
string.length >= attribute.range.start && string.length >= attribute.range.end,
'The range in $attribute is outside of the string $string',
);
}
return true;
}());
/// The plain string stored in the attributed string.
final String string;
/// The attributes this string carries.
///
/// The list must not be modified after this string is created.
final List<StringAttribute> attributes;
/// Returns a new [AttributedString] by concatenate the operands
///
/// The string attribute list of the returned [AttributedString] will contains
/// the string attributes from both operands with updated text ranges.
AttributedString operator +(AttributedString other) {
if (string.isEmpty) {
return other;
}
if (other.string.isEmpty) {
return this;
}
// None of the strings is empty.
final String newString = string + other.string;
final newAttributes = List<StringAttribute>.of(attributes);
if (other.attributes.isNotEmpty) {
final int offset = string.length;
for (final StringAttribute attribute in other.attributes) {
final newRange = TextRange(
start: attribute.range.start + offset,
end: attribute.range.end + offset,
);
final StringAttribute adjustedAttribute = attribute.copy(range: newRange);
newAttributes.add(adjustedAttribute);
}
}
return AttributedString(newString, attributes: newAttributes);
}
/// Two [AttributedString]s are equal if their string and attributes are.
@override
bool operator ==(Object other) {
return other.runtimeType == runtimeType &&
other is AttributedString &&
other.string == string &&
listEquals<StringAttribute>(other.attributes, attributes);
}
@override
int get hashCode => Object.hash(string, attributes);
@override
String toString() {
return "${objectRuntimeType(this, 'AttributedString')}('$string', attributes: $attributes)";
}
}
/// A [DiagnosticsProperty] for [AttributedString]s, which shows a string
/// when there are no attributes, and more details otherwise.
class AttributedStringProperty extends DiagnosticsProperty<AttributedString> {
/// Create a diagnostics property for an [AttributedString] object.
///
/// Such properties are used with [SemanticsData] objects.
AttributedStringProperty(
String super.name,
super.value, {
super.showName,
this.showWhenEmpty = false,
super.defaultValue,
super.level,
super.description,
});
/// Whether to show the property when the [value] is an [AttributedString]
/// whose [AttributedString.string] is the empty string.
///
/// This overrides [defaultValue].
final bool showWhenEmpty;
@override
bool get isInteresting =>
super.isInteresting && (showWhenEmpty || (value != null && value!.string.isNotEmpty));
@override
String valueToString({TextTreeConfiguration? parentConfiguration}) {
if (value == null) {
return 'null';
}
String text = value!.string;
if (parentConfiguration != null && !parentConfiguration.lineBreakProperties) {
// This follows a similar pattern to StringProperty.
text = text.replaceAll('\n', r'\n');
}
if (value!.attributes.isEmpty) {
return '"$text"';
}
return '"$text" ${value!.attributes}'; // the attributes will be in square brackets since they're a list
}
}
typedef _LabelPart = (String text, TextDirection? textDirection);
/// Builder for creating semantically correct concatenated labels with proper
/// text direction handling and spacing.
///
/// This builder helps address the complexity of concatenating multiple text
/// parts while handling language-specific nuances like RTL vs LTR text direction
/// and proper spacing.
///
/// Example usage:
/// ```dart