diff --git a/src/Controls/src/Core/BindableLayout/BindableLayout.cs b/src/Controls/src/Core/BindableLayout/BindableLayout.cs index 3201169cf6a5..774ab6b24995 100644 --- a/src/Controls/src/Core/BindableLayout/BindableLayout.cs +++ b/src/Controls/src/Core/BindableLayout/BindableLayout.cs @@ -380,6 +380,9 @@ void CreateChildren() return; } +#if IOS || MACCATALYST + using var contentRoleRefresh = BeginContentRoleRefresh(layout); +#endif if (TryAddEmptyView(layout, out IEnumerator enumerator)) { return; @@ -526,6 +529,9 @@ void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArg return; } +#if IOS || MACCATALYST + using var contentRoleRefresh = BeginContentRoleRefresh(layout); +#endif if (e.Action == NotifyCollectionChangedAction.Replace) { var index = e.OldStartingIndex; @@ -570,6 +576,13 @@ void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArg reset: CreateChildren); } +#if IOS || MACCATALYST + static Microsoft.Maui.Platform.SemanticExtensions.ContentRoleRefreshBatch BeginContentRoleRefresh(IBindableLayout layout) => + layout is IElement { Handler.PlatformView: UIKit.UIView } + ? Microsoft.Maui.Platform.SemanticExtensions.BeginContentRoleRefresh() + : null; +#endif + void ReplaceChild(object item, IBindableLayout layout, IList layoutChildren, int index) { var template = SelectTemplate(item, layout); diff --git a/src/Controls/src/Core/Compatibility/Handlers/VisualElementRenderer.cs b/src/Controls/src/Core/Compatibility/Handlers/VisualElementRenderer.cs index 0153313c5763..4c2ab47145b8 100644 --- a/src/Controls/src/Core/Compatibility/Handlers/VisualElementRenderer.cs +++ b/src/Controls/src/Core/Compatibility/Handlers/VisualElementRenderer.cs @@ -13,6 +13,7 @@ using Android.Content; using PlatformView = Android.Views.View; #elif IOS +using ContentSemantics = Microsoft.Maui.Platform.SemanticExtensions; using PlatformView = UIKit.UIView; #endif @@ -121,7 +122,17 @@ protected virtual void OnElementChanged(ElementChangedEventArgs e) protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (Element is TElement element && e.PropertyName != null) - _mapper.UpdateProperty(this, element, e.PropertyName); + { +#if IOS || MACCATALYST + if (e.PropertyName == AutomationProperties.ExcludedWithChildrenProperty.PropertyName + || e.PropertyName == nameof(IView.Visibility)) + ContentSemantics.UpdateContentRoleMapping(_mapper, this, element, e.PropertyName); + else +#endif + { + _mapper.UpdateProperty(this, element, e.PropertyName); + } + } ElementPropertyChanged?.Invoke(sender, e); ElementPropertyChangedPartial(sender, e); @@ -307,6 +318,9 @@ void IElementHandler.SetVirtualView(Maui.IElement view) // We use _virtualView as a WeakReference, and clear _tempElement _virtualView = _tempElement is null ? null : new(_tempElement); _tempElement = null; + + if (((IElementHandler)this).PlatformView is PlatformView platformView) + Microsoft.Maui.Platform.SemanticExtensions.RefreshAncestorContentRoles(platformView); } #else void IElementHandler.SetVirtualView(Maui.IElement view) => @@ -317,7 +331,39 @@ void IElementHandler.UpdateValue(string property) { if (Element is IElement element) { +#if IOS || MACCATALYST + bool isSemantics = property == nameof(IView.Semantics); + bool isOpacity = property == nameof(IView.Opacity); + bool isVisibility = property == nameof(IView.Visibility); + bool isAutomationRole = property == AutomationProperties.IsInAccessibleTreeProperty.PropertyName; + var previousView = isSemantics || isOpacity ? ((IElementHandler)this).PlatformView as PlatformView : null; + bool wasAccessibleLeaf = isSemantics && previousView is not null && ContentSemantics.IsAccessibleLeaf(this, previousView); + bool wasNonTransparent = isOpacity && previousView is not null && ContentSemantics.IsNonTransparent(this, previousView); + bool contentChanged = property == AutomationProperties.ExcludedWithChildrenProperty.PropertyName + || (property == nameof(IContentView.Content) && element is IContentView); + bool affectsRole = contentChanged || isSemantics || isOpacity || isVisibility || isAutomationRole; + using var refresh = affectsRole ? ContentSemantics.BeginContentRoleRefresh() : null; +#endif OnElementPropertyChanged(element, new PropertyChangedEventArgs(property)); +#if IOS || MACCATALYST + if (!affectsRole || !ReferenceEquals(Element, element) || ((IElementHandler)this).PlatformView is not PlatformView platformView) + return; + + // Derived renderers and event subscribers can change the native role after the mapper. + if (contentChanged) + { + ContentSemantics.RefreshContentSemantics(this); + ContentSemantics.RefreshAncestorContentRoles(platformView); + } + else if (isVisibility || isAutomationRole + || (isSemantics && (!wasAccessibleLeaf || !ReferenceEquals(previousView, platformView) + || !ContentSemantics.IsAccessibleLeaf(this, platformView))) + || (isOpacity && (!ReferenceEquals(previousView, platformView) + || wasNonTransparent != ContentSemantics.IsNonTransparent(this, platformView)))) + { + ContentSemantics.RefreshAncestorContentRoles(platformView); + } +#endif } } diff --git a/src/Controls/src/Core/Compatibility/Handlers/iOS/VisualElementRenderer.cs b/src/Controls/src/Core/Compatibility/Handlers/iOS/VisualElementRenderer.cs index aad33b3d4faf..712f0f1bccf8 100644 --- a/src/Controls/src/Core/Compatibility/Handlers/iOS/VisualElementRenderer.cs +++ b/src/Controls/src/Core/Compatibility/Handlers/iOS/VisualElementRenderer.cs @@ -6,7 +6,8 @@ namespace Microsoft.Maui.Controls.Handlers.Compatibility { - public abstract partial class VisualElementRenderer : UIView, IPlatformViewHandler, IElementHandler, IPlatformMeasureInvalidationController + public abstract partial class VisualElementRenderer : UIView, IPlatformViewHandler, IElementHandler, IPlatformMeasureInvalidationController, + Microsoft.Maui.Platform.IRefreshesContentRolesAfterMapping where TElement : Element, IView { bool _invalidateParentWhenMovedToWindow; diff --git a/src/Controls/src/Core/Element/Element.iOS.cs b/src/Controls/src/Core/Element/Element.iOS.cs index f9cfd5b7e035..bf7a69eaa133 100644 --- a/src/Controls/src/Core/Element/Element.iOS.cs +++ b/src/Controls/src/Core/Element/Element.iOS.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Maui.Handlers; using UIKit; namespace Microsoft.Maui.Controls @@ -10,6 +11,10 @@ public partial class Element { public static void MapAutomationPropertiesIsInAccessibleTree(IElementHandler handler, Element element) { + if (handler is IViewHandler viewHandler && ReferenceEquals(handler.VirtualView, element) + && Microsoft.Maui.Platform.SemanticExtensions.MapContentAccessibilityRole(viewHandler, AutomationProperties.GetIsInAccessibleTree(element))) + return; + // If the user hasn't set IsInAccessibleTree then just don't do anything if (!element.IsSet(AutomationProperties.IsInAccessibleTreeProperty)) return; @@ -28,6 +33,8 @@ public static void MapAutomationPropertiesIsInAccessibleTree(IElementHandler han var _defaultIsAccessibilityElement = Control.IsAccessibilityElement || Control is UIControl; Control.IsAccessibilityElement = (bool)((bool?)element.GetValue(AutomationProperties.IsInAccessibleTreeProperty) ?? _defaultIsAccessibilityElement); + if (handler is not (ElementHandler or Microsoft.Maui.Platform.IRefreshesContentRolesAfterMapping)) + Microsoft.Maui.Platform.SemanticExtensions.RefreshAncestorContentRoles(Control); } public static void MapAutomationPropertiesExcludedWithChildren(IElementHandler handler, Element view) @@ -39,6 +46,14 @@ public static void MapAutomationPropertiesExcludedWithChildren(IElementHandler h var _defaultAccessibilityElementsHidden = Control.AccessibilityElementsHidden || Control is UIControl; Control.AccessibilityElementsHidden = (bool)((bool?)view.GetValue(AutomationProperties.ExcludedWithChildrenProperty) ?? _defaultAccessibilityElementsHidden); + if (ReferenceEquals(handler.VirtualView, view) + && Microsoft.Maui.Platform.SemanticExtensions.IsMappingContentRole(handler, AutomationProperties.ExcludedWithChildrenProperty.PropertyName)) + return; + + if (handler is IViewHandler viewHandler && ReferenceEquals(handler.VirtualView, view)) + Microsoft.Maui.Platform.SemanticExtensions.ContentChanged(viewHandler); + else + Microsoft.Maui.Platform.SemanticExtensions.RefreshAncestorContentRoles(Control); } static void MapAutomationPropertiesIsInAccessibleTree(IElementHandler handler, IElement element) diff --git a/src/Controls/src/Core/Handlers/Items/iOS/GroupableItemsViewController.cs b/src/Controls/src/Core/Handlers/Items/iOS/GroupableItemsViewController.cs index 493fe9114fcd..3fa9f5719346 100644 --- a/src/Controls/src/Core/Handlers/Items/iOS/GroupableItemsViewController.cs +++ b/src/Controls/src/Core/Handlers/Items/iOS/GroupableItemsViewController.cs @@ -95,6 +95,7 @@ public override UICollectionReusableView GetViewForSupplementaryElement(UICollec break; } + (collectionView as MauiCollectionView)?.InvalidateAccessibilityContent(); return view; } diff --git a/src/Controls/src/Core/Handlers/Items/iOS/ItemsViewController.cs b/src/Controls/src/Core/Handlers/Items/iOS/ItemsViewController.cs index 368540ccf80b..2f70228246a4 100644 --- a/src/Controls/src/Core/Handlers/Items/iOS/ItemsViewController.cs +++ b/src/Controls/src/Core/Handlers/Items/iOS/ItemsViewController.cs @@ -159,6 +159,7 @@ public override UICollectionViewCell GetCell(UICollectionView collectionView, NS break; } + (collectionView as MauiCollectionView)?.InvalidateAccessibilityContent(); return cell; } @@ -1067,6 +1068,7 @@ private protected virtual NSIndexPath GetAdjustedIndexPathForItemSource(NSIndexP internal virtual void CellDisplayingEndedFromDelegate(UICollectionViewCell cell, NSIndexPath indexPath) { + (CollectionView as MauiCollectionView)?.InvalidateAccessibilityContent(); if (cell is TemplatedCell templatedCell && (templatedCell.PlatformHandler?.VirtualView as View)?.BindingContext is object bindingContext) { diff --git a/src/Controls/src/Core/Handlers/Items/iOS/MauiCollectionView.cs b/src/Controls/src/Core/Handlers/Items/iOS/MauiCollectionView.cs index 592887a2510e..b72c15b548b4 100644 --- a/src/Controls/src/Core/Handlers/Items/iOS/MauiCollectionView.cs +++ b/src/Controls/src/Core/Handlers/Items/iOS/MauiCollectionView.cs @@ -9,6 +9,8 @@ namespace Microsoft.Maui.Controls.Handlers.Items; public class MauiCollectionView : UICollectionView, IUIViewLifeCycleEvents, IPlatformMeasureInvalidationController { + bool _accessibilityContentChanged; + bool _layingOutSubviews; bool _invalidateParentWhenMovedToWindow; bool? _isSwipeEnabled; bool? _isBounceEnabled; @@ -236,9 +238,48 @@ public override void AddSubview(UIView view) // during the very first layout pass, before SetSwipeEnabled(false) below runs. We reapply on // every layout pass, for both enabled and disabled, since Bounces can otherwise revert to its // default (true) after UIKit reconfigures the embedded scroller. + internal void InvalidateAccessibilityContent() + { + if (_accessibilityContentChanged) + return; + + _accessibilityContentChanged = true; + if (!_layingOutSubviews) + SetNeedsLayout(); + } + + /// + public override void SubviewAdded(UIView uiview) + { + base.SubviewAdded(uiview); + InvalidateAccessibilityContent(); + } + + /// + public override void WillRemoveSubview(UIView uiview) + { + base.WillRemoveSubview(uiview); + InvalidateAccessibilityContent(); + } + public override void LayoutSubviews() { - base.LayoutSubviews(); + _layingOutSubviews = true; + try + { + base.LayoutSubviews(); + } + finally + { + _layingOutSubviews = false; + } + + if (_accessibilityContentChanged) + { + // Wait for UIKit to attach and remove deferred cells and supplementary views. + _accessibilityContentChanged = false; + Microsoft.Maui.Platform.SemanticExtensions.RefreshAncestorContentRoles(this); + } if (_isSwipeEnabled.HasValue) { diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/GroupableItemsViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/GroupableItemsViewController2.cs index 2e4b363cafda..3a21f9eeee1f 100644 --- a/src/Controls/src/Core/Handlers/Items2/iOS/GroupableItemsViewController2.cs +++ b/src/Controls/src/Core/Handlers/Items2/iOS/GroupableItemsViewController2.cs @@ -112,6 +112,7 @@ public override UICollectionReusableView GetViewForSupplementaryElement(UICollec break; } + (collectionView as Items.MauiCollectionView)?.InvalidateAccessibilityContent(); return view; } diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs index 689e445de50a..dca372333c9a 100644 --- a/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs +++ b/src/Controls/src/Core/Handlers/Items2/iOS/ItemsViewController2.cs @@ -141,6 +141,7 @@ public override UICollectionViewCell GetCell(UICollectionView collectionView, NS DefaultCell2.Label.Text = ItemsSource[indexpathAdjusted].ToString(); } + (collectionView as MauiCollectionView)?.InvalidateAccessibilityContent(); return cell; } @@ -861,6 +862,7 @@ private protected virtual NSIndexPath GetAdjustedIndexPathForItemSource(NSIndexP internal virtual void CellDisplayingEndedFromDelegate(UICollectionViewCell cell, NSIndexPath indexPath) { + (CollectionView as MauiCollectionView)?.InvalidateAccessibilityContent(); if (cell is TemplatedCell2 templatedCell2 && (templatedCell2.PlatformHandler?.VirtualView as View)?.BindingContext is { } bindingContext) { diff --git a/src/Controls/src/Core/Handlers/Items2/iOS/StructuredItemsViewController2.cs b/src/Controls/src/Core/Handlers/Items2/iOS/StructuredItemsViewController2.cs index 6cd2eb54b383..484d7964e330 100644 --- a/src/Controls/src/Core/Handlers/Items2/iOS/StructuredItemsViewController2.cs +++ b/src/Controls/src/Core/Handlers/Items2/iOS/StructuredItemsViewController2.cs @@ -112,6 +112,7 @@ public override UICollectionReusableView GetViewForSupplementaryElement(UICollec break; } + (collectionView as Items.MauiCollectionView)?.InvalidateAccessibilityContent(); return view; } diff --git a/src/Controls/src/Core/Platform/GestureManager/GesturePlatformManager.iOS.cs b/src/Controls/src/Core/Platform/GestureManager/GesturePlatformManager.iOS.cs index cf2f54e71ccc..3b92470e6463 100644 --- a/src/Controls/src/Core/Platform/GestureManager/GesturePlatformManager.iOS.cs +++ b/src/Controls/src/Core/Platform/GestureManager/GesturePlatformManager.iOS.cs @@ -768,6 +768,7 @@ void LoadRecognizers() bool dragFound = false; bool dropFound = false; + bool addedButtonTrait = false; if (PlatformView != null && _handler.VirtualView is View v && (v.HasAccessibleTapGesture() || v.HasAccessibleLongPressGesture()) && @@ -775,6 +776,7 @@ _handler.VirtualView is View v && { PlatformView.AccessibilityTraits |= UIAccessibilityTrait.Button; _addedFlags |= UIAccessibilityTrait.Button; + addedButtonTrait = true; // Ensure container views are marked as accessibility elements so VoiceOver // can announce the Button trait and make the container focusable for VoiceOver. @@ -801,57 +803,6 @@ _handler.VirtualView is View v && _setShouldGroupAccessibilityChildren = true; } - // UIKit's default accessibilityActivate() simulates touch events which are intermittently - // unreliable for UITapGestureRecognizer (especially on macOS Catalyst Ctrl+Option+Space). - // Bypass that path by directly invoking SendTapped on the MAUI TapGestureRecognizer for - // both iOS and Catalyst. VoiceOver activation is a single semantic event — UIKit's - // simulated-touch path also does not honor NumberOfTapsRequired > 1 from a VoiceOver - // activation, so the direct path does not regress that scenario and makes activation - // reliable across both platforms. - // This block is decoupled from the grouping block above so it also registers when - // SemanticExtensions already promoted the container (layout with Hint + gesture). - // Note: Only Microsoft.Maui.Platform.MauiView exposes AccessibilityActivateCallback, - // so layouts whose platform view is not a MauiView (e.g. Border, ScrollView, custom - // container handlers) fall back to UIKit's default simulated-touch activation path. - if (PlatformView is Microsoft.Maui.Platform.MauiView mauiView && - _handler.VirtualView is global::Microsoft.Maui.ILayout) - { - var weakThis = new WeakReference(this); - - mauiView.AccessibilityActivateCallback = () => - { - if (!weakThis.TryGetTarget(out var manager)) - { - return false; - } - - var view = manager._handler?.VirtualView as View; - - if (view is null) - { - return false; - } - - // Honor the same gates UIKit's touch dispatch would have applied. VoiceOver - // activation bypasses UIKit's hit-testing/touch path, so without these - // guards a disabled or input-transparent layout would still fire its tap. - if (!view.IsEnabled || view.InputTransparent) - { - return false; - } - - if (view.HasAccessibleTapGesture(out var tap)) - { - tap.SendTapped(view); - return true; - } - - return false; - }; - - _setAccessibilityActivateCallback = true; - } - if (OperatingSystem.IsIOSVersionAtLeast(13) || OperatingSystem.IsMacCatalystVersionAtLeast(13) #if TVOS || OperatingSystem.IsTvOSVersionAtLeast(11) @@ -863,6 +814,17 @@ _handler.VirtualView is View v && } } + if (!_setAccessibilityActivateCallback && + PlatformView is Microsoft.Maui.Platform.MauiView mauiView && + _handler.VirtualView is View activatableView && + (activatableView is global::Microsoft.Maui.ILayout + ? addedButtonTrait + : Microsoft.Maui.Platform.SemanticExtensions.UsesContentSemantics(mauiView, activatableView) + && activatableView.HasAccessibleTapGesture())) + { + ConnectAccessibilityActivateCallback(mauiView); + } + _interactions.Clear(); for (int i = 0; i < ElementGestureRecognizers.Count; i++) @@ -1013,13 +975,96 @@ _handler.VirtualView is View v && } } + void ConnectAccessibilityActivateCallback(Microsoft.Maui.Platform.MauiView mauiView) + { + // UIKit's simulated-touch activation is unreliable for tap recognizers on Mac Catalyst. + var weakThis = new WeakReference(this); + mauiView.AccessibilityActivateCallback = () => + { + if (!weakThis.TryGetTarget(out var manager) || + manager._handler.VirtualView is not View view || !view.IsEnabled || view.InputTransparent || + (view is not global::Microsoft.Maui.ILayout && manager.PlatformView?.IsAccessibilityElement != true) || + !view.HasAccessibleTapGesture(out var tap)) + { + return false; + } + + if (view is global::Microsoft.Maui.ILayout) + { + tap.SendTapped(view); + return true; + } + + // Snapshot before sending: an action or event can change the recognizer collection. + var gestures = view.GestureRecognizers; + List? additionalTaps = null; + bool foundFirst = false; + for (int i = 0; i < gestures.Count; i++) + { + if (gestures[i] is not TapGestureRecognizer candidate || !candidate.IsAccessibleTapGesture()) + continue; + + if (foundFirst) + (additionalTaps ??= new()).Add(candidate); + foundFirst = true; + } + + // Direct activation has no touch, but UIKit supplies its activation point in screen coordinates. + if (manager.PlatformView is not UIView nativeView) + return false; + + var window = nativeView.Window; + var screenPoint = nativeView.AccessibilityActivationPoint; + var bounds = nativeView.Bounds; + var windowPoint = window?.ConvertPointFromWindow(screenPoint, null); + var localPoint = windowPoint is { } point + ? nativeView.ConvertPointFromView(point, window) + : new CGPoint(bounds.GetMidX(), bounds.GetMidY()); + var source = new WeakReference(nativeView); + var sourceWindow = window is not null ? new WeakReference(window) : null; + Point? GetPosition(IElement? relativeTo) + { + if (relativeTo is null) + return windowPoint is { } position ? new Point(position.X, position.Y) : null; + + if (relativeTo.Handler?.PlatformView is not UIView target) + return null; + if (source.TryGetTarget(out var native) && ReferenceEquals(native, target)) + return new Point(localPoint.X, localPoint.Y); + if (windowPoint is { } location && sourceWindow?.TryGetTarget(out var nativeWindow) == true + && target.Window == nativeWindow) + { + var converted = target.ConvertPointFromView(location, nativeWindow); + return new Point(converted.X, converted.Y); + } + + return null; + } + + tap.SendTapped(view, GetPosition); + if (additionalTaps is not null) + { + foreach (var additionalTap in additionalTaps) + additionalTap.SendTapped(view, GetPosition); + } + return true; + }; + _setAccessibilityActivateCallback = true; + } + void OnTapGestureRecognizerPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { - if (e.Is(TapGestureRecognizer.ButtonsProperty)) + if ((e.Is(TapGestureRecognizer.ButtonsProperty) || e.Is(TapGestureRecognizer.NumberOfTapsRequiredProperty)) + && Microsoft.Maui.Platform.SemanticExtensions.RefreshContentSemantics(_handler)) + { + GestureRecognizersOnCollectionChanged(null, new(NotifyCollectionChangedAction.Reset)); + } + else if (e.Is(TapGestureRecognizer.ButtonsProperty)) { LoadRecognizers(); } - else if (e.Is(TapGestureRecognizer.NumberOfTapsRequiredProperty) && sender is TapGestureRecognizer tapGesture) + + if (e.Is(TapGestureRecognizer.NumberOfTapsRequiredProperty) && sender is TapGestureRecognizer tapGesture) { UpdateNumberOfTapsRequired(tapGesture); } @@ -1185,6 +1230,7 @@ void GestureRecognizersOnCollectionChanged(object? sender, NotifyCollectionChang _addedFlags = UIAccessibilityTrait.None; _defaultAccessibilityRespondsToUserInteraction = null; + Microsoft.Maui.Platform.SemanticExtensions.RefreshContentSemantics(_handler); LoadRecognizers(); } diff --git a/src/Controls/src/Core/Platform/SemanticExtensions.cs b/src/Controls/src/Core/Platform/SemanticExtensions.cs index 9ba68c0d569d..5af4058d35e2 100644 --- a/src/Controls/src/Core/Platform/SemanticExtensions.cs +++ b/src/Controls/src/Core/Platform/SemanticExtensions.cs @@ -13,17 +13,19 @@ internal static bool HasAccessibleTapGesture( { foreach (var gesture in virtualView.GestureRecognizers) { - //Accessibility can't handle Tap Recognizers with > 1 tap - if (gesture is TapGestureRecognizer tgr && tgr.NumberOfTapsRequired == 1) + if (gesture is TapGestureRecognizer tgr && tgr.IsAccessibleTapGesture()) { tapGestureRecognizer = tgr; - return (tgr.Buttons & ButtonsMask.Primary) == ButtonsMask.Primary; + return true; } } tapGestureRecognizer = null; return false; } + internal static bool IsAccessibleTapGesture(this TapGestureRecognizer tap) => + tap.NumberOfTapsRequired == 1 && (tap.Buttons & ButtonsMask.Primary) == ButtonsMask.Primary; + internal static bool HasAccessibleLongPressGesture(this View virtualView) => HasAccessibleLongPressGesture(virtualView, out _); diff --git a/src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt b/src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt index 53af1e100334..1ed133d5d3ab 100644 --- a/src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt +++ b/src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +override Microsoft.Maui.Controls.Handlers.Items.MauiCollectionView.SubviewAdded(UIKit.UIView! uiview) -> void +override Microsoft.Maui.Controls.Handlers.Items.MauiCollectionView.WillRemoveSubview(UIKit.UIView! uiview) -> void ~override Microsoft.Maui.Controls.Platform.Compatibility.ShellFlyoutContentRenderer.TraitCollectionDidChange(UIKit.UITraitCollection previousTraitCollection) -> void ~static Microsoft.Maui.Controls.ResourceDictionary.CreateMergedDictionary(Microsoft.Maui.Controls.ResourceDictionary mergeTarget) -> T override Microsoft.Maui.Controls.Handlers.Items2.ItemsViewController2.ViewDidLayoutSubviews() -> void diff --git a/src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt b/src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt index 53af1e100334..1ed133d5d3ab 100644 --- a/src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt +++ b/src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +override Microsoft.Maui.Controls.Handlers.Items.MauiCollectionView.SubviewAdded(UIKit.UIView! uiview) -> void +override Microsoft.Maui.Controls.Handlers.Items.MauiCollectionView.WillRemoveSubview(UIKit.UIView! uiview) -> void ~override Microsoft.Maui.Controls.Platform.Compatibility.ShellFlyoutContentRenderer.TraitCollectionDidChange(UIKit.UITraitCollection previousTraitCollection) -> void ~static Microsoft.Maui.Controls.ResourceDictionary.CreateMergedDictionary(Microsoft.Maui.Controls.ResourceDictionary mergeTarget) -> T override Microsoft.Maui.Controls.Handlers.Items2.ItemsViewController2.ViewDidLayoutSubviews() -> void diff --git a/src/Controls/src/Core/VisualElement/VisualElement.cs b/src/Controls/src/Core/VisualElement/VisualElement.cs index 6e7843c8cff7..800fff3e13ec 100644 --- a/src/Controls/src/Core/VisualElement/VisualElement.cs +++ b/src/Controls/src/Core/VisualElement/VisualElement.cs @@ -1990,6 +1990,12 @@ void IPropertyPropagationController.PropagatePropertyChanged(string propertyName this.RefreshPropertyValue(InputTransparentProperty, _inputTransparentExplicit); var effectiveVisibilityChanged = false; +#if IOS || MACCATALYST + using var visibilityRefresh = (propertyName == null || propertyName == IsVisibleProperty.PropertyName) + && Handler?.PlatformView is UIKit.UIView + ? Microsoft.Maui.Platform.SemanticExtensions.BeginContentRoleRefresh() + : null; +#endif if (propertyName == null || propertyName == IsVisibleProperty.PropertyName) effectiveVisibilityChanged = UpdateEffectiveVisibility(); diff --git a/src/Controls/src/Core/VisualElement/VisualElement.iOS.cs b/src/Controls/src/Core/VisualElement/VisualElement.iOS.cs index 5195d1ae8978..2faeb9b249f5 100644 --- a/src/Controls/src/Core/VisualElement/VisualElement.iOS.cs +++ b/src/Controls/src/Core/VisualElement/VisualElement.iOS.cs @@ -1,7 +1,12 @@ -namespace Microsoft.Maui.Controls +using Microsoft.Maui.Controls.Platform; +using Microsoft.Maui.Platform; + +namespace Microsoft.Maui.Controls { - public partial class VisualElement + public partial class VisualElement : IContentViewAccessibility { - + bool IContentViewAccessibility.HasAccessibleGesture => + this is View view && (view.HasAccessibleTapGesture() || view.HasAccessibleLongPressGesture()); + bool? IContentViewAccessibility.IsInAccessibleTree => AutomationProperties.GetIsInAccessibleTree(this); } } \ No newline at end of file diff --git a/src/Controls/tests/Core.UnitTests/SemanticPropertyUnitTests.cs b/src/Controls/tests/Core.UnitTests/SemanticPropertyUnitTests.cs index f6e97eb3e2f1..9880178dfbd8 100644 --- a/src/Controls/tests/Core.UnitTests/SemanticPropertyUnitTests.cs +++ b/src/Controls/tests/Core.UnitTests/SemanticPropertyUnitTests.cs @@ -9,6 +9,28 @@ namespace Microsoft.Maui.Controls.Core.UnitTests { public class SemanticPropertyUnitTests : BaseTestFixture { + [Fact] + public void HasAccessibleTapGesture_SecondaryTapDoesNotHideLaterPrimaryTap() + { + var view = new Border(); + view.GestureRecognizers.Add(new TapGestureRecognizer { Buttons = ButtonsMask.Secondary }); + var primary = new TapGestureRecognizer { Buttons = ButtonsMask.Primary }; + view.GestureRecognizers.Add(primary); + + Assert.True(Platform.SemanticExtensions.HasAccessibleTapGesture(view, out var tap)); + Assert.Same(primary, tap); + } + + [Fact] + public void HasAccessibleTapGesture_SecondaryOnlyIsNotAccessible() + { + var view = new Border(); + view.GestureRecognizers.Add(new TapGestureRecognizer { Buttons = ButtonsMask.Secondary }); + view.GestureRecognizers.Add(new TapGestureRecognizer { NumberOfTapsRequired = 2 }); + + Assert.False(Platform.SemanticExtensions.HasAccessibleTapGesture(view, out _)); + } + [Fact] public void FakeBindSemanticProperties_PropertiesPropagate() { diff --git a/src/Controls/tests/DeviceTests/Elements/Accessibility/ContentAccessibilityTests.iOS.cs b/src/Controls/tests/DeviceTests/Elements/Accessibility/ContentAccessibilityTests.iOS.cs new file mode 100644 index 000000000000..1f0d184ee89d --- /dev/null +++ b/src/Controls/tests/DeviceTests/Elements/Accessibility/ContentAccessibilityTests.iOS.cs @@ -0,0 +1,1399 @@ +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Threading.Tasks; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Handlers; +using Microsoft.Maui.Platform; +using UIKit; +using Xunit; +using static Microsoft.Maui.DeviceTests.AssertHelpers; + +namespace Microsoft.Maui.DeviceTests; + +[Category(TestCategory.Accessibility)] +[Collection(ControlsHandlerTestBase.RunInNewWindowCollection)] +public class ContentAccessibilityTests : ControlsHandlerTestBase +{ + [Fact] + public async Task RadioButtonWithoutSemanticTextKeepsNativeAccessibility() + { + var radio = new RadioButton { IsChecked = true }; + var handler = await CreateHandlerAsync(radio); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.Equal("1", handler.PlatformView.AccessibilityValue); + }); + } + + [Fact] + public async Task AccessibleGesturesChangeContentAccessibilityRole() + { + var border = new Border { Content = new Button { Text = "Child action" } }; + SemanticProperties.SetDescription(border, "Actions"); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + border.GestureRecognizers.Add(new PanGestureRecognizer()); + SemanticProperties.SetDescription(border, "More actions"); + Assert.False(handler.PlatformView.IsAccessibilityElement); + + var tap = new TapGestureRecognizer(); + border.GestureRecognizers.Add(tap); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.True((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Button) != 0); + tap.NumberOfTapsRequired = 2; + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Button) == 0); + tap.NumberOfTapsRequired = 1; + Assert.True(handler.PlatformView.IsAccessibilityElement); + tap.Buttons = ButtonsMask.Secondary; + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.False((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Button) != 0); + tap.Buttons = ButtonsMask.Primary; + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.True((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Button) != 0); + border.GestureRecognizers.Remove(tap); + Assert.False(handler.PlatformView.IsAccessibilityElement); + + var longPress = new LongPressGestureRecognizer(); + border.GestureRecognizers.Add(longPress); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.True((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Button) != 0); + border.GestureRecognizers.Remove(longPress); + Assert.False(handler.PlatformView.IsAccessibilityElement); + }); + } + + [Fact] + public async Task DecorativeContentKeepsParentDescriptionFocusable() + { + var view = new ContentView { Content = new BoxView() }; + SemanticProperties.SetDescription(view, "Decorative swatch"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.Equal("Decorative swatch", handler.PlatformView.AccessibilityLabel); + }); + } + + [Fact] + public async Task ReplacingContentRemapsAccessibilityRole() + { + var border = new Border(); + SemanticProperties.SetDescription(border, "Actions"); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + border.Content = new Button { Text = "Child action" }; + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + border.Content = null; + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.Equal("Actions", handler.PlatformView.AccessibilityLabel); + }); + } + + [Fact] + public async Task ContentRoleUsesFinalMappedContent() + { + var view = new ContentView { Content = new Button { Text = "Initial action" } }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + view.Content = new BoxView(); + view.Content = new Button { Text = "Replaced action" }; + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.Equal("Actions", handler.PlatformView.AccessibilityLabel); + }); + } + + sealed class DecorativeContentViewHandler : ContentViewHandler + { + public DecorativeContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IContentView.Content), (handler, _) => + { + foreach (var subview in handler.PlatformView.Subviews) + subview.RemoveFromSuperview(); + handler.PlatformView.AddSubview(new UIView()); + }); + return mapper; + } + } + + [Fact] + public async Task BorderRoleUsesFinalMappedContent() + { + var border = new Border { Content = new BoxView() }; + SemanticProperties.SetDescription(border, "Actions"); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + border.Content = new Button { Text = "Replaced action" }; + Assert.False(Assert.Single(handler.PlatformView.Subviews).IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class DecorativeBorderHandler : BorderHandler + { + public DecorativeBorderHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IBorderView.Content), (handler, _) => + { + foreach (var subview in handler.PlatformView.Subviews) + subview.RemoveFromSuperview(); + handler.PlatformView.AddSubview(new UIView()); + }); + return mapper; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ScrollViewRoleUsesFinalMappedContent(bool replaceMapping) + { + var scrollView = new ScrollView + { + AutomationId = replaceMapping ? "ReplaceContent" : "AppendContent", + Content = new Button { AutomationId = "HiddenAction", Text = "Initial action" }, + }; + SemanticProperties.SetDescription(scrollView, "Actions"); + var handler = await CreateHandlerAsync(scrollView); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.GetContentView()?.AccessibilityElementsHidden); + Assert.True(handler.PlatformView.IsAccessibilityElement); + + scrollView.Content = new Button { Text = "Visible action" }; + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + + scrollView.Content = new Button { AutomationId = "HiddenAction", Text = "Replaced action" }; + Assert.True(handler.PlatformView.GetContentView()?.AccessibilityElementsHidden); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + Assert.Equal("Actions", handler.PlatformView.AccessibilityLabel); + }); + } + + sealed class CustomizedScrollViewHandler : ScrollViewHandler + { + public CustomizedScrollViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.ModifyMapping(nameof(IScrollView.Content), (handler, scrollView, next) => + { + if (scrollView.AutomationId == "ReplaceContent") + { + handler.PlatformView.GetContentView()?.RemoveFromSuperview(); + handler.PlatformView.AddSubview(new UIView { Tag = MauiScrollView.ContentTag, IsAccessibilityElement = true }); + } + else + { + next?.Invoke(handler, scrollView); + } + + if (handler.PlatformView.GetContentView() is { } content) + content.AccessibilityElementsHidden = scrollView.PresentedContent?.AutomationId == "HiddenAction"; + }); + return mapper; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LayoutAddRefreshesAncestorAfterEffectiveCommand(bool replaceMapping) + { + var layout = new Grid { AutomationId = replaceMapping ? "ReplaceAdd" : "AppendAdd" }; + var view = new ContentView { Content = layout }; + SemanticProperties.SetDescription(view, "Actions"); + var layoutHandler = await CreateHandlerAsync(layout); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(layoutHandler, layout.Handler); + Assert.True(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + layout.Add(new Button { Text = "Action" }); + Assert.Equal(!replaceMapping, Assert.Single(layoutHandler.PlatformView.Subviews).AccessibilityElementsHidden); + Assert.Equal(!replaceMapping, handler.PlatformView.IsAccessibilityElement); + Assert.Equal(count + 1, handler.SemanticsUpdates); + }); + } + + sealed class ExcludingLayoutHandler : LayoutHandler + { + public ExcludingLayoutHandler() : base(commandMapper: CreateCommandMapper()) + { + } + + static CommandMapper CreateCommandMapper() + { + var mapper = new CommandMapper(CommandMapper); + mapper.ModifyMapping(nameof(ILayoutHandler.Add), (handler, layout, args, next) => + { + if (layout.AutomationId == "ReplaceAdd" && args is LayoutHandlerUpdate replacement) + { + handler.PlatformView.AddSubview(replacement.View.ToPlatform(handler.MauiContext!)); + return; + } + + next?.Invoke(handler, layout, args); + if (args is LayoutHandlerUpdate update && update.View.Handler?.PlatformView is UIView child) + child.AccessibilityElementsHidden = true; + }); + return mapper; + } + } + + [Fact] + public async Task NestedVisibilityAndChildMutationsRemapAccessibilityRole() + { + var button = new Button { Text = "Child action" }; + var layout = new VerticalStackLayout { Children = { button } }; + var border = new Border { Content = layout }; + SemanticProperties.SetDescription(border, "Actions"); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + button.IsVisible = false; + Assert.True(handler.PlatformView.IsAccessibilityElement); + button.IsVisible = true; + Assert.False(handler.PlatformView.IsAccessibilityElement); + button.Opacity = 0; + Assert.True(handler.PlatformView.IsAccessibilityElement); + button.Opacity = 1; + Assert.False(handler.PlatformView.IsAccessibilityElement); + layout.Clear(); + Assert.True(handler.PlatformView.IsAccessibilityElement); + layout.Add(button); + Assert.False(handler.PlatformView.IsAccessibilityElement); + }); + } + + [Fact] + public async Task RevealingPopulatedLayoutRefreshesContentHostOnce() + { + var layout = new Grid(); + for (int i = 0; i < 16; i++) + layout.Add(new BoxView()); + var inner = new ContentView { Content = new Button { Text = "Action" } }; + SemanticProperties.SetDescription(inner, "Inner actions"); + var parent = new Grid { layout, inner }; + var view = new ContentView { Content = parent }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + parent.IsVisible = false; + Assert.Equal(count + 1, handler.SemanticsUpdates); + Assert.True(handler.PlatformView.IsAccessibilityElement); + parent.IsVisible = true; + Assert.Equal(count + 2, handler.SemanticsUpdates); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(Assert.IsAssignableFrom(inner.Handler?.PlatformView).ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task BindableLayoutPopulationRefreshesContentHostOnce() + { + var layout = new VerticalStackLayout(); + BindableLayout.SetItemTemplate(layout, new DataTemplate(() => new Button { Text = "Action" })); + var view = new ContentView { Content = layout }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + BindableLayout.SetItemsSource(layout, new int[16]); + Assert.Equal(16, layout.Children.Count); + Assert.Equal(count + 1, handler.SemanticsUpdates); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task BindableLayoutRangeAddRefreshesContentHostOnce() + { + var items = new RangeObservableCollection(); + var layout = new VerticalStackLayout(); + BindableLayout.SetItemTemplate(layout, new DataTemplate(() => new Button { Text = "Action" })); + BindableLayout.SetItemsSource(layout, items); + var view = new ContentView { Content = layout }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + items.AddRange(new[] { 1, 2, 3 }); + Assert.Equal(3, layout.Children.Count); + Assert.Equal(count + 1, handler.SemanticsUpdates); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class RangeObservableCollection : ObservableCollection + { + public void AddRange(int[] values) + { + var index = Count; + foreach (var value in values) + Items.Add(value); + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, values, index)); + } + } + + [Fact] + public async Task ReincludingSubtreeRestoresItsContentRole() + { + var button = new Button { Text = "Action" }; + var border = new Border { Content = button }; + SemanticProperties.SetDescription(border, "Actions"); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + AutomationProperties.SetExcludedWithChildren(border, true); + button.IsVisible = false; + button.IsVisible = true; + AutomationProperties.SetExcludedWithChildren(border, false); + Assert.False(handler.PlatformView.AccessibilityElementsHidden); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task UpdatingAccessibleButtonTextDoesNotRemapAncestorRole() + { + var button = new Button { Text = "Action" }; + SemanticProperties.SetDescription(button, "First"); + var view = new ContentView { Content = new Grid { button } }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + SemanticProperties.SetDescription(button, "Second"); + Assert.Equal("Second", Assert.IsAssignableFrom(button.Handler?.PlatformView).AccessibilityLabel); + Assert.Equal(count, handler.SemanticsUpdates); + }); + } + + [Fact] + public async Task UpdatingAccessibleBorderTextDoesNotRemapAncestorRole() + { + var item = new Border + { + Content = new Label { Text = "Action" }, + GestureRecognizers = { new TapGestureRecognizer() }, + }; + SemanticProperties.SetDescription(item, "First"); + var view = new ContentView { Content = new Grid { item } }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + var native = Assert.IsAssignableFrom(item.Handler?.PlatformView); + Assert.True(native.IsAccessibilityElement); + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + SemanticProperties.SetDescription(item, "Second"); + Assert.Equal("Second", native.AccessibilityLabel); + Assert.True(native.IsAccessibilityElement); + Assert.Equal(count, handler.SemanticsUpdates); + }); + } + + [Fact] + public async Task AncestorRoleUsesFinalMappedCompatibilityOpacity() + { + var child = new BoxView(); + var view = new ContentView { Content = child }; + SemanticProperties.SetDescription(view, "Actions"); + var renderer = await CreateHandlerAsync(child); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(renderer, child.Handler); + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + child.Opacity = 0; + Assert.True(renderer.Alpha > 0); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.Equal(count, handler.SemanticsUpdates); + }); + } + + sealed class MinimumOpacityRenderer : Microsoft.Maui.Controls.Handlers.Compatibility.ViewRenderer + { + public MinimumOpacityRenderer() : base(CreateMapper()) + { + } + + protected override void OnElementChanged(ElementChangedEventArgs e) + { + base.OnElementChanged(e); + if (e.NewElement is not null && Control is null) + SetNativeControl(new UILabel { Text = "Action", IsAccessibilityElement = true }); + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(VisualElementRendererMapper); + mapper.AppendToMapping(nameof(IView.Opacity), (handler, _) => + { + if (handler.ContainerView is UIView wrapper && wrapper.Alpha == 0) + wrapper.Alpha = 0.1f; + }); + return mapper; + } + } + + [Fact] + public async Task UpdatingAccessibleCompatibilityTextDoesNotRemapAncestorRole() + { + var child = new BoxView(); + SemanticProperties.SetDescription(child, "First"); + var view = new ContentView { Content = new Grid { child } }; + SemanticProperties.SetDescription(view, "Actions"); + var renderer = await CreateHandlerAsync(child); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + var native = Assert.IsAssignableFrom(((IElementHandler)renderer).PlatformView); + Assert.Same(renderer, child.Handler); + Assert.True(native.IsAccessibilityElement); + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + SemanticProperties.SetDescription(child, "Second"); + Assert.Equal("Second", native.AccessibilityLabel); + Assert.True(native.IsAccessibilityElement); + Assert.Equal(count, handler.SemanticsUpdates); + }); + } + + [Fact] + public async Task AncestorRoleUsesFinalMappedExclusion() + { + var button = new Button { Text = "Action" }; + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var buttonHandler = await CreateHandlerAsync(button); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(buttonHandler, button.Handler); + Assert.False(handler.PlatformView.IsAccessibilityElement); + AutomationProperties.SetExcludedWithChildren(button, true); + Assert.False(buttonHandler.PlatformView.AccessibilityElementsHidden); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class ExposesExcludedButtonHandler : ButtonHandler + { + public ExposesExcludedButtonHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(AutomationProperties.ExcludedWithChildrenProperty.PropertyName, + (handler, _) => handler.PlatformView.AccessibilityElementsHidden = false); + return mapper; + } + } + + [Fact] + public async Task ExplicitVisibilityRemapRefreshesAncestorFromFinalState() + { + var button = new Button { Text = "Action" }; + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var buttonHandler = await CreateHandlerAsync(button); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(buttonHandler, button.Handler); + Assert.False(handler.PlatformView.IsAccessibilityElement); + buttonHandler.HideWhenMapped = true; + buttonHandler.UpdateValue(nameof(IView.Visibility)); + Assert.True(buttonHandler.PlatformView.Hidden); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class VisibilityOverrideButtonHandler : ButtonHandler + { + public bool HideWhenMapped { get; set; } + + public VisibilityOverrideButtonHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Visibility), + (handler, _) => handler.PlatformView.Hidden = ((VisibilityOverrideButtonHandler)handler).HideWhenMapped); + return mapper; + } + } + + [Fact] + public async Task AncestorRoleUsesFinalMappedAutomationInclusion() + { + var button = new Button { Text = "Action" }; + AutomationProperties.SetIsInAccessibleTree(button, false); + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var buttonHandler = await CreateHandlerAsync(button); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(buttonHandler, button.Handler); + Assert.True(handler.PlatformView.IsAccessibilityElement); + AutomationProperties.SetIsInAccessibleTree(button, true); + Assert.False(buttonHandler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task ContentRoleDoesNotRefreshAncestorDuringAutomationAppend() + { + var child = new ContentView { Content = new BoxView() }; + SemanticProperties.SetDescription(child, "Child"); + AutomationProperties.SetIsInAccessibleTree(child, false); + var view = new ContentView { Content = child }; + SemanticProperties.SetDescription(view, "Actions"); + var childHandler = await CreateHandlerAsync(child); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(childHandler, child.Handler); + Assert.True(handler.PlatformView.IsAccessibilityElement); + int count = handler.SemanticsUpdates; + childHandler.BeforeExclusion = () => Assert.Equal(count, handler.SemanticsUpdates); + AutomationProperties.SetIsInAccessibleTree(child, true); + Assert.False(childHandler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class AutomationExcludingContentViewHandler : ContentViewHandler + { + public Action? BeforeExclusion { get; set; } + + public AutomationExcludingContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(AutomationProperties.IsInAccessibleTreeProperty.PropertyName, (handler, content) => + { + if (content is BindableObject bindable && AutomationProperties.GetIsInAccessibleTree(bindable) == true) + { + ((AutomationExcludingContentViewHandler)handler).BeforeExclusion?.Invoke(); + handler.PlatformView.IsAccessibilityElement = false; + } + }); + return mapper; + } + } + + [Fact] + public async Task ExcludingAnAccessibleButtonFromItsSemanticsMapperRefreshesAncestorRole() + { + var button = new Button { Text = "Action" }; + SemanticProperties.SetDescription(button, "First"); + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var buttonHandler = await CreateHandlerAsync(button); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(buttonHandler, button.Handler); + Assert.True(buttonHandler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetDescription(button, "Exclude from semantics"); + Assert.False(buttonHandler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class ExcludedButtonHandler : ButtonHandler + { + public ExcludedButtonHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(AutomationProperties.IsInAccessibleTreeProperty.PropertyName, + (handler, button) => + { + if (button is BindableObject bindable && AutomationProperties.GetIsInAccessibleTree(bindable) == true) + handler.PlatformView.IsAccessibilityElement = false; + }); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, button) => + { + if (button.Semantics?.Description == "Exclude from semantics") + handler.PlatformView.IsAccessibilityElement = false; + }); + return mapper; + } + } + + [Fact] + public async Task ContentRoleRechecksDescendantVisibilityChangedByItsMapper() + { + var button = new Button { Text = "Action", IsVisible = false }; + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(button.IsVisible); + Assert.True(handler.PlatformView.IsAccessibilityElement); + button.IsVisible = true; + Assert.False(button.IsVisible); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class HidesChildContentViewHandler : ContentViewHandler + { + public HidesChildContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Semantics), (_, view) => + { + if (view.PresentedContent is Button button) + button.IsVisible = false; + }); + return mapper; + } + } + + [Fact] + public async Task AncestorRoleUsesFinalMappedOpacity() + { + var button = new Button { Text = "Action" }; + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var buttonHandler = await CreateHandlerAsync(button); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(buttonHandler, button.Handler); + Assert.False(handler.PlatformView.IsAccessibilityElement); + var count = handler.SemanticsUpdates; + button.Opacity = 0; + Assert.True(buttonHandler.PlatformView.Alpha > 0); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.Equal(count, handler.SemanticsUpdates); + }); + } + + sealed class MinimumOpacityButtonHandler : ButtonHandler + { + public MinimumOpacityButtonHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Opacity), (handler, _) => + { + if (handler.PlatformView.Alpha == 0) + handler.PlatformView.Alpha = 0.1f; + }); + return mapper; + } + } + + [Fact] + public async Task PositiveOpacityChangesDoNotRefreshAncestorSemantics() + { + var button = new Button { Text = "Action" }; + var view = new ContentView { Content = button }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + var count = handler.SemanticsUpdates; + button.Opacity = 0.5; + button.Opacity = 0.25; + Assert.Equal(count, handler.SemanticsUpdates); + button.Opacity = 0; + Assert.Equal(count + 1, handler.SemanticsUpdates); + Assert.True(handler.PlatformView.IsAccessibilityElement); + button.Opacity = 1; + Assert.Equal(count + 2, handler.SemanticsUpdates); + Assert.False(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class CountingContentViewHandler : ContentViewHandler + { + public int SemanticsUpdates { get; private set; } + + public CountingContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, _) => ((CountingContentViewHandler)handler).SemanticsUpdates++); + return mapper; + } + } + + [Fact] + public async Task DeferredCollectionItemsRemapAncestorAccessibilityRole() + { + var collection = new CollectionView + { + ItemTemplate = new DataTemplate(() => new Button { Text = "Child action", HeightRequest = 44 }), + }; + var border = new Border { Content = collection, HeightRequest = 120, WidthRequest = 120 }; + SemanticProperties.SetDescription(border, "Actions"); + + await CreateHandlerAndAddToWindow(border, async handler => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + collection.ItemsSource = new[] { "Action" }; + + await AssertEventually(() => !handler.PlatformView.IsAccessibilityElement && + handler.PlatformView.ShouldGroupAccessibilityChildren, timeout: 5000); + var native = Assert.IsAssignableFrom(collection.Handler?.PlatformView); + native.LayoutSubviews(); + int count = handler.SemanticsUpdates; + native.LayoutSubviews(); + native.LayoutSubviews(); + Assert.Equal(count, handler.SemanticsUpdates); + + collection.ItemsSource = Array.Empty(); + await AssertEventually(() => handler.PlatformView.IsAccessibilityElement && + !handler.PlatformView.ShouldGroupAccessibilityChildren, timeout: 5000); + }); + } + + sealed class CountingBorderHandler : BorderHandler + { + public int SemanticsUpdates { get; private set; } + + public CountingBorderHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, _) => ((CountingBorderHandler)handler).SemanticsUpdates++); + return mapper; + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ExplicitAccessibilityRoleSurvivesSemanticsRemapping(bool include) + { + var view = new ContentView { Content = new Button { Text = "Child action" } }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + AutomationProperties.SetIsInAccessibleTree(view, include); + Assert.Equal(include, handler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetHint(view, "Choose an action"); + Assert.Equal(include, handler.PlatformView.IsAccessibilityElement); + view.Content = new BoxView(); + Assert.Equal(include, handler.PlatformView.IsAccessibilityElement); + view.ClearValue(AutomationProperties.IsInAccessibleTreeProperty); + Assert.True(handler.PlatformView.IsAccessibilityElement); + view.Content = new Button { Text = "Another child action" }; + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task PreconfiguredAccessibilityRoleDoesNotBecomeTheNativeDefault() + { + var view = new ContentView { Content = new Button { Text = "Child action" } }; + AutomationProperties.SetIsInAccessibleTree(view, true); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetDescription(view, "Actions"); + view.ClearValue(AutomationProperties.IsInAccessibleTreeProperty); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task AccessibilityActivateInvokesBorderTap() + { + var border = new Border { Content = new Label { Text = "Action" } }; + SemanticProperties.SetDescription(border, "Action"); + var tap = new TapGestureRecognizer(); + int taps = 0; + tap.Tapped += (sender, _) => + { + Assert.Same(border, sender); + taps++; + }; + border.GestureRecognizers.Add(tap); + + var handler = await CreateHandlerAsync(border); + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.True(handler.PlatformView.AccessibilityActivate()); + Assert.Equal(1, taps); + }); + } + + [Theory] + [InlineData("Eligible", true)] + [InlineData("Ineligible", false)] + [InlineData("Empty", false)] + public async Task ContentRoleRecognizesExplicitNativeAccessibilityElements(string mode, bool hasAccessibleChild) + { + var child = new BoxView { AutomationId = mode }; + var parent = new Border { Content = child }; + SemanticProperties.SetDescription(parent, "Chart"); + var childHandler = await CreateHandlerAsync(child); + var parentHandler = await CreateHandlerAsync(parent); + + await InvokeOnMainThreadAsync(() => + { + Assert.Same(childHandler, child.Handler); + Assert.False(childHandler.PlatformView.IsAccessibilityElement); + Assert.Equal(mode == "Empty", childHandler.PlatformView.Subviews.Length != 0); + Assert.Equal(!hasAccessibleChild, parentHandler.PlatformView.IsAccessibilityElement); + Assert.Equal(hasAccessibleChild, parentHandler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + sealed class NativeAccessibilityContainerHandler : ViewHandler + { + public NativeAccessibilityContainerHandler() : base(ViewMapper) + { + } + + protected override UIView CreatePlatformView() + { + var view = new UIView(); + using var key = new Foundation.NSString("accessibilityElements"); + using var entry = new UIAccessibilityElement(view) + { + AccessibilityLabel = "Chart segment", + IsAccessibilityElement = VirtualView?.AutomationId == "Eligible", + }; + bool empty = VirtualView?.AutomationId == "Empty"; + if (empty) + view.AddSubview(new UILabel { Text = "Suppressed", IsAccessibilityElement = true }); + using var elements = empty ? Foundation.NSArray.FromNSObjects(Array.Empty()) + : Foundation.NSArray.FromNSObjects(entry); + view.SetValueForKey(elements, key); + return view; + } + } + + [Fact] + public async Task AccessibilityActivateUsesNativeActivationPoint() + { + var tap = new TapGestureRecognizer(); + var border = new Border + { + Content = new Label { Text = "Action" }, + GestureRecognizers = { tap }, + }; + var parent = new ContentView { Content = border, Padding = new Thickness(18, 30) }; + SemanticProperties.SetDescription(border, "Action"); + TappedEventArgs? tapped = null; + tap.Tapped += (_, args) => tapped = args; + + await CreateHandlerAndAddToWindow(parent, handler => + { + var native = Assert.IsAssignableFrom(border.Handler?.PlatformView); + var window = Assert.IsAssignableFrom(native.Window); + var point = new CoreGraphics.CGPoint(12, 24); + var windowPoint = native.ConvertPointToView(point, window); + var parentPoint = native.ConvertPointToView(point, handler.PlatformView); + Assert.NotEqual(point, parentPoint); + native.AccessibilityActivationPoint = window.ConvertPointToWindow(windowPoint, null); + Assert.Equal(window.ConvertPointToWindow(windowPoint, null), native.AccessibilityActivationPoint); + + Assert.True(native.AccessibilityActivate()); + var args = Assert.IsType(tapped); + Assert.Equal(new Microsoft.Maui.Graphics.Point(point.X, point.Y), args.GetPosition(border)); + Assert.Equal(new Microsoft.Maui.Graphics.Point(parentPoint.X, parentPoint.Y), args.GetPosition(parent)); + Assert.Equal(new Microsoft.Maui.Graphics.Point(windowPoint.X, windowPoint.Y), args.GetPosition(null)); + }); + } + + [Fact] + public async Task AccessibilityActivateInvokesAllPrimarySingleTapsOnBorder() + { + var border = new Border { Content = new Label { Text = "Action" } }; + SemanticProperties.SetDescription(border, "Action"); + var first = new TapGestureRecognizer(); + var second = new TapGestureRecognizer { Buttons = ButtonsMask.Primary | ButtonsMask.Secondary }; + var secondary = new TapGestureRecognizer { Buttons = ButtonsMask.Secondary }; + var doubleTap = new TapGestureRecognizer { NumberOfTapsRequired = 2 }; + int firstTaps = 0, secondTaps = 0, otherTaps = 0; + first.Tapped += (_, _) => + { + firstTaps++; + border.GestureRecognizers.Remove(first); + }; + second.Tapped += (_, _) => secondTaps++; + secondary.Tapped += (_, _) => otherTaps++; + doubleTap.Tapped += (_, _) => otherTaps++; + border.GestureRecognizers.Add(first); + border.GestureRecognizers.Add(secondary); + border.GestureRecognizers.Add(second); + border.GestureRecognizers.Add(doubleTap); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(Assert.IsType>(handler.PlatformView.AccessibilityActivateCallback)()); + Assert.Equal(1, firstTaps); + Assert.Equal(1, secondTaps); + Assert.Equal(0, otherTaps); + }); + } + + [Fact] + public async Task AccessibilityActivateCallbackRespectsBorderExclusion() + { + var border = new Border { Content = new Label { Text = "Action" } }; + SemanticProperties.SetDescription(border, "Action"); + var tap = new TapGestureRecognizer(); + int taps = 0; + tap.Tapped += (_, _) => taps++; + border.GestureRecognizers.Add(tap); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + AutomationProperties.SetIsInAccessibleTree(border, false); + Assert.False(handler.PlatformView.IsAccessibilityElement); + Assert.False(Assert.IsType>(handler.PlatformView.AccessibilityActivateCallback)()); + Assert.Equal(0, taps); + + border.ClearValue(AutomationProperties.IsInAccessibleTreeProperty); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.True(Assert.IsType>(handler.PlatformView.AccessibilityActivateCallback)()); + Assert.Equal(1, taps); + }); + } + + [Fact] + public async Task DescendantChangePreservesAppSemanticsMapperRole() + { + var button = new Button { Text = "Child action" }; + var layout = new VerticalStackLayout { Children = { button } }; + var view = new ContentView { Content = layout }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + button.Opacity = 0; + button.Opacity = 1; + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.False(handler.PlatformView.ShouldGroupAccessibilityChildren); + }); + } + + [Fact] + public async Task AncestorRoleUsesOriginatingSemanticsMapperFinalState() + { + var inner = new ContentView { Content = new BoxView() }; + SemanticProperties.SetDescription(inner, "Inner"); + var outer = new ContentView { Content = inner }; + SemanticProperties.SetDescription(outer, "Outer"); + + var innerHandler = await CreateHandlerAsync(inner); + var outerHandler = await CreateHandlerAsync(outer); + await InvokeOnMainThreadAsync(() => + { + Assert.Same(innerHandler, inner.Handler); + Assert.False(innerHandler.PlatformView.IsAccessibilityElement); + Assert.True(outerHandler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetHint(inner, "New hint"); + Assert.False(innerHandler.PlatformView.IsAccessibilityElement); + Assert.True(outerHandler.PlatformView.IsAccessibilityElement); + }); + } + + [Fact] + public async Task AncestorRoleUsesCompatibilityRendererFinalState() + { + var inner = new ContentView { Content = new BoxView() }; + SemanticProperties.SetDescription(inner, "Inner"); + var outer = new ContentView { Content = inner }; + SemanticProperties.SetDescription(outer, "Outer"); + + var renderer = await CreateHandlerAsync(inner); + var handler = await CreateHandlerAsync(outer); + await InvokeOnMainThreadAsync(() => + { + Assert.Same(renderer, inner.Handler); + var native = Assert.IsAssignableFrom(((IElementHandler)renderer).PlatformView); + Assert.False(native.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + + renderer.BeforeExclusion = () => Assert.True(handler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetHint(inner, "New hint"); + + Assert.Equal("New hint", native.AccessibilityHint); + Assert.False(native.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class ExcludedContentViewRenderer : Microsoft.Maui.Controls.Handlers.Compatibility.ViewRenderer + { + public Action? BeforeExclusion { get; set; } + + public ExcludedContentViewRenderer() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(VisualElementRendererMapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, _) => + { + ((ExcludedContentViewRenderer)handler).BeforeExclusion?.Invoke(); + if (handler.PlatformView is UIView native) + native.IsAccessibilityElement = false; + }); + return mapper; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AncestorRoleUsesFinalRendererCallbackState(bool useEvent) + { + var inner = new BoxView(); + SemanticProperties.SetDescription(inner, "Show"); + var outer = new ContentView { Content = inner }; + SemanticProperties.SetDescription(outer, "Actions"); + var renderer = await CreateHandlerAsync(inner); + var handler = await CreateHandlerAsync(outer); + + await InvokeOnMainThreadAsync(() => + { + var native = Assert.IsAssignableFrom(((IElementHandler)renderer).PlatformView); + Assert.True(native.IsAccessibilityElement); + Assert.False(handler.PlatformView.IsAccessibilityElement); + if (useEvent) + renderer.ElementPropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(IView.Semantics)) + native.IsAccessibilityElement = false; + }; + else + renderer.ExcludeOnSemantics = true; + + SemanticProperties.SetHint(inner, "Hide"); + + Assert.False(native.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class CallbackExcludingRenderer : Microsoft.Maui.Controls.Handlers.Compatibility.ViewRenderer + { + public bool ExcludeOnSemantics { get; set; } + + protected override void OnElementChanged(ElementChangedEventArgs e) + { + base.OnElementChanged(e); + if (e.NewElement is not null && Control is null) + SetNativeControl(new UILabel { Text = "Action", IsAccessibilityElement = true }); + } + + protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) + { + base.OnElementPropertyChanged(sender, e); + if (ExcludeOnSemantics && e.PropertyName == nameof(IView.Semantics)) + Control!.IsAccessibilityElement = false; + } + } + +#pragma warning disable CS0618 // Frame and its renderer are obsolete but supported for compatibility. + [Fact] + public async Task ReplacingCompatibilityContentRestoresParentFocus() + { + var frame = new Frame { Content = new Button { Text = "Action" } }; + var renderer = await CreateHandlerAsync(frame); + + await InvokeOnMainThreadAsync(() => + { + SemanticProperties.SetDescription(frame, "Actions"); + var native = Assert.IsAssignableFrom(((IElementHandler)renderer).PlatformView); + Assert.False(native.IsAccessibilityElement); + Assert.True(native.ShouldGroupAccessibilityChildren); + + frame.Content = new BoxView(); + + Assert.True(native.IsAccessibilityElement); + Assert.False(native.ShouldGroupAccessibilityChildren); + Assert.Equal("Actions", native.AccessibilityLabel); + }); + } +#pragma warning restore CS0618 + + [Fact] + public async Task AncestorRoleTracksCompatibilityLeafExclusion() + { + var child = new BoxView(); + SemanticProperties.SetDescription(child, "Included"); + var view = new ContentView { Content = child }; + SemanticProperties.SetDescription(view, "Actions"); + var renderer = await CreateHandlerAsync(child); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + var native = Assert.IsAssignableFrom(((IElementHandler)renderer).PlatformView); + Assert.True(native.IsAccessibilityElement); + Assert.False(handler.PlatformView.IsAccessibilityElement); + SemanticProperties.SetDescription(child, "Excluded"); + Assert.False(native.IsAccessibilityElement); + Assert.True(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class ConditionalLeafRenderer : Microsoft.Maui.Controls.Handlers.Compatibility.ViewRenderer + { + public ConditionalLeafRenderer() : base(CreateMapper()) + { + } + + protected override void OnElementChanged(ElementChangedEventArgs e) + { + base.OnElementChanged(e); + if (e.NewElement is not null && Control is null) + SetNativeControl(new UILabel { Text = "Action", IsAccessibilityElement = true }); + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(VisualElementRendererMapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, child) => + { + if (handler.PlatformView is UILabel native && SemanticProperties.GetDescription(child) == "Excluded") + native.IsAccessibilityElement = false; + }); + return mapper; + } + } + + sealed class ExcludedContentViewHandler : ContentViewHandler + { + public ExcludedContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, _) => handler.PlatformView.IsAccessibilityElement = false); + return mapper; + } + } + + sealed class CustomRoleContentViewHandler : ContentViewHandler + { + public CustomRoleContentViewHandler() : base(CreateMapper()) + { + } + + static PropertyMapper CreateMapper() + { + var mapper = new PropertyMapper(Mapper); + mapper.AppendToMapping(nameof(IView.Semantics), (handler, _) => + { + handler.PlatformView.IsAccessibilityElement = true; + handler.PlatformView.ShouldGroupAccessibilityChildren = false; + }); + return mapper; + } + } + + [Fact] + public async Task ReplacementSemanticsMapperDoesNotSuppressExplicitAccessibilityRole() + { + var view = new ContentView { Content = new Button { Text = "Child action" } }; + SemanticProperties.SetDescription(view, "Actions"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + Assert.False(handler.PlatformView.IsAccessibilityElement); + AutomationProperties.SetIsInAccessibleTree(view, true); + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.Equal("Actions", handler.PlatformView.AccessibilityLabel); + view.ClearValue(AutomationProperties.IsInAccessibleTreeProperty); + Assert.False(handler.PlatformView.IsAccessibilityElement); + }); + } + + sealed class TextOnlyContentViewHandler : ContentViewHandler + { + public TextOnlyContentViewHandler() : base(new PropertyMapper(Mapper) + { + [nameof(IView.Semantics)] = (handler, view) => handler.PlatformView.AccessibilityLabel = view.Semantics?.Description, + }) + { + } + } + + [Fact] + public async Task GroupedContentKeepsItsOwnSemanticText() + { + var child = new Button { Text = "Child action" }; + var view = new ContentView { Content = child }; + SemanticProperties.SetHint(view, "Choose an action"); + var handler = await CreateHandlerAsync(view); + + await InvokeOnMainThreadAsync(() => + { + var native = handler.PlatformView; + Assert.False(native.IsAccessibilityElement); + Assert.True(native.ShouldGroupAccessibilityChildren); + var nativeChild = Assert.IsAssignableFrom(child.Handler?.PlatformView); + Assert.True(nativeChild.IsAccessibilityElement); + Assert.Null(native.AccessibilityLabel); + Assert.Equal("Choose an action", native.AccessibilityHint); + + SemanticProperties.SetDescription(view, "Actions"); + Assert.Equal("Actions", native.AccessibilityLabel); + view.ClearValue(SemanticProperties.DescriptionProperty); + view.ClearValue(SemanticProperties.HintProperty); + Assert.False(native.ShouldGroupAccessibilityChildren); + Assert.Null(native.AccessibilityLabel); + Assert.Null(native.AccessibilityHint); + + SemanticProperties.SetHint(view, "Choose again"); + Assert.True(native.ShouldGroupAccessibilityChildren); + Assert.Equal("Choose again", native.AccessibilityHint); + }); + } + + [Fact] + public async Task HeadingRetainsAnAccessibleFocusStop() + { + var border = new Border { Content = new Button { Text = "Child action" } }; + SemanticProperties.SetDescription(border, "Actions"); + SemanticProperties.SetHeadingLevel(border, SemanticHeadingLevel.Level1); + var handler = await CreateHandlerAsync(border); + + await InvokeOnMainThreadAsync(() => + { + Assert.True(handler.PlatformView.IsAccessibilityElement); + Assert.True((handler.PlatformView.AccessibilityTraits & UIAccessibilityTrait.Header) != 0); + }); + } +} diff --git a/src/Controls/tests/TestCases.HostApp/Issues/Issue33612.cs b/src/Controls/tests/TestCases.HostApp/Issues/Issue33612.cs new file mode 100644 index 000000000000..75f6fbe4baa2 --- /dev/null +++ b/src/Controls/tests/TestCases.HostApp/Issues/Issue33612.cs @@ -0,0 +1,94 @@ +using System.Collections.ObjectModel; + +namespace Maui.Controls.Sample.Issues; + +[Issue(IssueTracker.Github, 33612, "Inconsistent Accessibility Behavior Across Platforms - a container with SemanticProperties.Description/Hint should not collapse its independently-accessible children", PlatformAffected.All)] +public class Issue33612 : ContentPage +{ + public ObservableCollection Items { get; } = new() + { + new SuggestionItem("Item1", "First item"), + new SuggestionItem("Item2", "Second item"), + new SuggestionItem("Item3", "Third item"), + }; + + Label _tappedItemLabel; + + public Issue33612() + { + BindingContext = this; + + _tappedItemLabel = new Label + { + AutomationId = "TappedItemLabel", + Text = "None" + }; + + var itemsLayout = new VerticalStackLayout + { + AutomationId = "SuggestionsItemsLayout" + }; + itemsLayout.SetBinding(BindableLayout.ItemsSourceProperty, new Binding(nameof(Items))); + BindableLayout.SetItemTemplate(itemsLayout, CreateItemTemplate()); + + // Outer structural container: has its own Description ("Suggestions") but must not hide + // the individually-accessible items inside it (root cause of #33612). + var suggestionsContainer = new ContentView + { + AutomationId = "SuggestionsContainer", + Content = new ScrollView { Content = itemsLayout } + }; + SemanticProperties.SetDescription(suggestionsContainer, "Suggestions"); + + Content = new VerticalStackLayout + { + Children = { suggestionsContainer, _tappedItemLabel } + }; + } + + DataTemplate CreateItemTemplate() + { + return new DataTemplate(() => + { + var label = new Label + { + HorizontalOptions = LayoutOptions.Center, + VerticalOptions = LayoutOptions.Center + }; + label.SetBinding(Label.TextProperty, new Binding(nameof(SuggestionItem.Text))); + + // Each item is its own actionable unit: it owns a gesture recognizer, so it should + // remain a normal leaf accessibility element carrying its own Description/Hint, + // rather than being treated as a passive structural wrapper. + var border = new Border + { + Padding = 12, + Margin = 6, + Content = label + }; + // AutomationId is intentionally distinct from the visible text so tests can locate the + // Border unambiguously without matching the inner Label or a phantom accessibility element. + border.SetBinding(AutomationIdProperty, new Binding(nameof(SuggestionItem.AutomationId))); + border.SetBinding(SemanticProperties.DescriptionProperty, new Binding(nameof(SuggestionItem.Text))); + SemanticProperties.SetHint(border, "Double tap to activate"); + + var tapGestureRecognizer = new TapGestureRecognizer(); + tapGestureRecognizer.Tapped += OnSuggestionTapped; + border.GestureRecognizers.Add(tapGestureRecognizer); + + return border; + }); + } + + async void OnSuggestionTapped(object sender, TappedEventArgs e) + { + if (sender is Border tappedBorder && tappedBorder.BindingContext is SuggestionItem item) + { + _tappedItemLabel.Text = item.Text; + } + + await DisplayAlert("Suggestion Selected", "is a suggestion tap event", "OK"); + } + + public record SuggestionItem(string AutomationId, string Text); +} diff --git a/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue33612.cs b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue33612.cs new file mode 100644 index 000000000000..221f0ac745f4 --- /dev/null +++ b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue33612.cs @@ -0,0 +1,50 @@ +#if !WINDOWS +using NUnit.Framework; +using UITest.Appium; +using UITest.Core; + +namespace Microsoft.Maui.TestCases.Tests.Issues; + +public class Issue33612 : _IssuesUITest +{ + public Issue33612(TestDevice device) : base(device) { } + + public override string Issue => "Inconsistent Accessibility Behavior Across Platforms - a container with SemanticProperties.Description/Hint should not collapse its independently-accessible children"; + + [Test] + [Category(UITestCategories.Accessibility)] + public void ContainerDescriptionDoesNotHideIndividuallyAccessibleItems() + { + App.WaitForElement("SuggestionsContainer"); + + // AutomationIds are intentionally distinct from the visible text so this can't be satisfied + // by the inner Label alone — it proves the Border itself is reachable. + App.WaitForElement("Item1"); + App.WaitForElement("Item2"); + App.WaitForElement("Item3"); + } + + [Test] + [Category(UITestCategories.Accessibility)] + public void TappingSuggestionItemStillInvokesItsOwnGesture() + { + App.WaitForElement("SuggestionsContainer"); + var firstItem = App.WaitForElement("Item1"); + + if (Device == TestDevice.Mac) + { + var itemBounds = firstItem.GetRect(); + App.TapCoordinates(itemBounds.CenterX(), itemBounds.CenterY()); + } + else + { + App.Tap("Item1"); + } + + App.WaitForElement("OK"); + App.Tap("OK"); + var tappedItemText = App.WaitForElement("TappedItemLabel").GetText(); + Assert.That(tappedItemText, Is.EqualTo("First item")); + } +} +#endif diff --git a/src/Core/src/Handlers/Border/BorderHandler.iOS.cs b/src/Core/src/Handlers/Border/BorderHandler.iOS.cs index 8324f96f6de5..97f4afd3edd7 100644 --- a/src/Core/src/Handlers/Border/BorderHandler.iOS.cs +++ b/src/Core/src/Handlers/Border/BorderHandler.iOS.cs @@ -68,6 +68,8 @@ static partial void UpdateContent(IBorderHandler handler) platformView.AddSubview(platformContent); } } + + SemanticExtensions.ContentMapped(handler); } } } \ No newline at end of file diff --git a/src/Core/src/Handlers/ContentView/ContentViewHandler.iOS.cs b/src/Core/src/Handlers/ContentView/ContentViewHandler.iOS.cs index 023a40b2befe..1847f1e6334b 100644 --- a/src/Core/src/Handlers/ContentView/ContentViewHandler.iOS.cs +++ b/src/Core/src/Handlers/ContentView/ContentViewHandler.iOS.cs @@ -67,6 +67,7 @@ static void UpdateContent(IContentViewHandler handler) public static partial void MapContent(IContentViewHandler handler, IContentView page) { UpdateContent(handler); + SemanticExtensions.ContentMapped(handler); } protected override void DisconnectHandler(ContentView platformView) diff --git a/src/Core/src/Handlers/Element/ElementHandler.cs b/src/Core/src/Handlers/Element/ElementHandler.cs index 58a3fe8da35e..0631af4bc0e8 100644 --- a/src/Core/src/Handlers/Element/ElementHandler.cs +++ b/src/Core/src/Handlers/Element/ElementHandler.cs @@ -128,6 +128,18 @@ public virtual void SetVirtualView(IElement view) } _handlerState = ElementHandlerState.Connected; +#if __IOS__ || MACCATALYST + if (this is IViewHandler contentHandler && Platform.SemanticExtensions.RefreshesAfterContentMapping(this)) + { + using var refresh = Platform.SemanticExtensions.BeginContentRoleRefresh(); + Platform.SemanticExtensions.RefreshContentSemantics(contentHandler); + RefreshAncestorContentRoles(); + } + else + { + RefreshAncestorContentRoles(); + } +#endif } public virtual void UpdateValue(string property) @@ -135,14 +147,70 @@ public virtual void UpdateValue(string property) if (VirtualView == null) return; +#if __IOS__ || MACCATALYST + if (property == nameof(IView.Semantics) && this is IViewHandler handler && PlatformView is UIKit.UIView platformView) + { + bool wasAccessibleLeaf = Platform.SemanticExtensions.IsAccessibleLeaf(handler, platformView); + _mapper?.UpdateProperty(this, VirtualView, property); + // A non-leaf mapper can change accessible descendants without changing this view's flags. + if (!wasAccessibleLeaf || !ReferenceEquals(platformView, PlatformView) + || !Platform.SemanticExtensions.IsAccessibleLeaf(handler, platformView)) + RefreshAncestorContentRoles(); + return; + } + + if (property == nameof(IView.Opacity) && this is IViewHandler opacityHandler && PlatformView is UIKit.UIView opacityView) + { + bool wasNonTransparent = Platform.SemanticExtensions.IsNonTransparent(opacityHandler, opacityView); + _mapper?.UpdateProperty(this, VirtualView, property); + if (PlatformView is UIKit.UIView updatedView + && (!ReferenceEquals(opacityView, updatedView) + || wasNonTransparent != Platform.SemanticExtensions.IsNonTransparent(opacityHandler, updatedView))) + RefreshAncestorContentRoles(); + return; + } + + if (this is IViewHandler roleHandler && (property is nameof(IView.Visibility) or Platform.SemanticExtensions.ExcludedWithChildrenPropertyName + || (property == nameof(IContentView.Content) && Platform.SemanticExtensions.RefreshesAfterContentMapping(this)))) + { + Platform.SemanticExtensions.UpdateContentRoleMapping(_mapper, this, VirtualView, property); + if (property == nameof(IView.Visibility)) + RefreshAncestorContentRoles(); + else + Platform.SemanticExtensions.ContentChanged(roleHandler); + return; + } +#endif _mapper?.UpdateProperty(this, VirtualView, property); +#if __IOS__ || MACCATALYST + if (property == nameof(Platform.IContentViewAccessibility.IsInAccessibleTree)) + RefreshAncestorContentRoles(); +#endif } +#if __IOS__ || MACCATALYST + void RefreshAncestorContentRoles() + { + if (this is IViewHandler && PlatformView is UIKit.UIView platformView) + Platform.SemanticExtensions.RefreshAncestorContentRoles(platformView); + } +#endif + public virtual void Invoke(string command, object? args) { if (VirtualView == null) return; +#if __IOS__ || MACCATALYST + if (this is LayoutHandler && command is nameof(ILayoutHandler.Add) or nameof(ILayoutHandler.Remove) + or nameof(ILayoutHandler.Insert) or nameof(ILayoutHandler.Update) or nameof(ILayoutHandler.Clear)) + { + using var refresh = Platform.SemanticExtensions.BeginContentRoleRefresh(); + _commandMapper?.Invoke(this, VirtualView, command, args); + RefreshAncestorContentRoles(); + return; + } +#endif _commandMapper?.Invoke(this, VirtualView, command, args); } diff --git a/src/Core/src/Handlers/Layout/LayoutHandler.iOS.cs b/src/Core/src/Handlers/Layout/LayoutHandler.iOS.cs index 385375633e2b..90e6d0baf83a 100644 --- a/src/Core/src/Handlers/Layout/LayoutHandler.iOS.cs +++ b/src/Core/src/Handlers/Layout/LayoutHandler.iOS.cs @@ -40,6 +40,7 @@ public override void SetVirtualView(IView view) } PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void Add(IView child) @@ -58,6 +59,7 @@ public void Add(IView child) } PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void Remove(IView child) @@ -71,12 +73,14 @@ public void Remove(IView child) } PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void Clear() { PlatformView.ClearSubviews(); PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void Insert(int index, IView child) @@ -95,6 +99,7 @@ public void Insert(int index, IView child) } PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void Update(int index, IView child) @@ -109,6 +114,7 @@ public void Update(int index, IView child) PlatformView.InsertSubview(child.ToPlatform(MauiContext), targetIndex); PlatformView.SetNeedsLayout(); PlatformView.InvalidateAncestorsMeasures(); + SemanticExtensions.RefreshAncestorContentRoles(PlatformView); } public void UpdateZIndex(IView child) diff --git a/src/Core/src/Handlers/RefreshView/RefreshViewHandler.iOS.cs b/src/Core/src/Handlers/RefreshView/RefreshViewHandler.iOS.cs index b714d0347296..2a6d09c1829d 100644 --- a/src/Core/src/Handlers/RefreshView/RefreshViewHandler.iOS.cs +++ b/src/Core/src/Handlers/RefreshView/RefreshViewHandler.iOS.cs @@ -53,7 +53,10 @@ public static void MapIsRefreshing(IRefreshViewHandler handler, IRefreshView ref => handler.PlatformView.IsRefreshing = handler.VirtualView.IsRefreshing; public static void MapContent(IRefreshViewHandler handler, IRefreshView refreshView) - => UpdateContent(handler); + { + UpdateContent(handler); + SemanticExtensions.ContentMapped(handler); + } public static void MapRefreshColor(IRefreshViewHandler handler, IRefreshView refreshView) => UpdateRefreshColor(handler); diff --git a/src/Core/src/Handlers/ScrollView/ScrollViewHandler.iOS.cs b/src/Core/src/Handlers/ScrollView/ScrollViewHandler.iOS.cs index 535d5f15d6f2..b55084cf5c2f 100644 --- a/src/Core/src/Handlers/ScrollView/ScrollViewHandler.iOS.cs +++ b/src/Core/src/Handlers/ScrollView/ScrollViewHandler.iOS.cs @@ -136,6 +136,7 @@ public static void MapContent(IScrollViewHandler handler, IScrollView scrollView // We'll use the local cross-platform layout methods defined in our handler (which wrap the ScrollView's default methods) // so we can normalize the behavior of the scrollview to match the other platforms UpdateContentView(scrollView, handler); + SemanticExtensions.ContentMapped(handler); } // We don't actually have this mapped because we don't need it, but we can't remove it because it's public diff --git a/src/Core/src/Handlers/SwipeItemView/SwipeItemViewHandler.iOS.cs b/src/Core/src/Handlers/SwipeItemView/SwipeItemViewHandler.iOS.cs index 4d0dc435bfca..ed3cb4cbcfd2 100644 --- a/src/Core/src/Handlers/SwipeItemView/SwipeItemViewHandler.iOS.cs +++ b/src/Core/src/Handlers/SwipeItemView/SwipeItemViewHandler.iOS.cs @@ -39,7 +39,10 @@ void UpdateContent() public static void MapContent(ISwipeItemViewHandler handler, ISwipeItemView page) { if (handler is SwipeItemViewHandler platformHandler) + { platformHandler.UpdateContent(); + SemanticExtensions.ContentMapped(handler); + } } public static void MapVisibility(ISwipeItemViewHandler handler, ISwipeItemView view) diff --git a/src/Core/src/Handlers/SwipeView/SwipeViewHandler.iOS.cs b/src/Core/src/Handlers/SwipeView/SwipeViewHandler.iOS.cs index 3dd5b216a5a3..2f099bd0a74f 100644 --- a/src/Core/src/Handlers/SwipeView/SwipeViewHandler.iOS.cs +++ b/src/Core/src/Handlers/SwipeView/SwipeViewHandler.iOS.cs @@ -22,6 +22,7 @@ public static void MapContent(ISwipeViewHandler handler, ISwipeView view) _ = handler.VirtualView ?? throw new InvalidOperationException($"{nameof(VirtualView)} should have been set by base class."); handler.PlatformView.UpdateContent(view, handler.MauiContext); + SemanticExtensions.ContentMapped(handler); } public static void MapIsEnabled(ISwipeViewHandler handler, ISwipeView swipeView) diff --git a/src/Core/src/Handlers/View/ViewHandler.cs b/src/Core/src/Handlers/View/ViewHandler.cs index 7999914d7642..853bc4b0d602 100644 --- a/src/Core/src/Handlers/View/ViewHandler.cs +++ b/src/Core/src/Handlers/View/ViewHandler.cs @@ -514,6 +514,11 @@ public static void MapVisibility(IViewHandler handler, IView view) #endif ((PlatformView?)handler.PlatformView)?.UpdateVisibility(view); +#if __IOS__ || MACCATALYST + if (!SemanticExtensions.IsMappingContentRole(handler, nameof(IView.Visibility)) + && handler.PlatformView is PlatformView platformView) + SemanticExtensions.RefreshAncestorContentRoles(platformView); +#endif } /// @@ -575,6 +580,12 @@ public static void MapOpacity(IViewHandler handler, IView view) return; #endif +#if __IOS__ || MACCATALYST + var platformView = handler is not (ElementHandler or IRefreshesContentRolesAfterMapping) + ? handler.PlatformView as PlatformView : null; + bool wasNonTransparent = platformView is not null && SemanticExtensions.IsNonTransparent(handler, platformView); +#endif + if (handler.HasContainer) { ((PlatformView?)handler.ContainerView)?.UpdateOpacity(view); @@ -583,6 +594,11 @@ public static void MapOpacity(IViewHandler handler, IView view) } else ((PlatformView?)handler.PlatformView)?.UpdateOpacity(view); + +#if __IOS__ || MACCATALYST + if (platformView is not null && wasNonTransparent != SemanticExtensions.IsNonTransparent(handler, platformView)) + SemanticExtensions.RefreshAncestorContentRoles(platformView); +#endif } /// @@ -647,6 +663,12 @@ public static void MapSemantics(IViewHandler handler, IView view) { MappingSemantics(handler, view); ((PlatformView?)handler.PlatformView)?.UpdateSemantics(view); +#if __IOS__ || MACCATALYST + // Independent handlers may not have a post-mapping path. + if (handler is not (ElementHandler or IRefreshesContentRolesAfterMapping) + && handler.PlatformView is PlatformView platformView) + SemanticExtensions.RefreshAncestorContentRoles(platformView); +#endif } /// diff --git a/src/Core/src/Platform/iOS/SemanticExtensions.cs b/src/Core/src/Platform/iOS/SemanticExtensions.cs index 0256b7d3e92a..f668d0ac4310 100644 --- a/src/Core/src/Platform/iOS/SemanticExtensions.cs +++ b/src/Core/src/Platform/iOS/SemanticExtensions.cs @@ -1,11 +1,118 @@ using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; +using Foundation; +using Microsoft.Maui.Handlers; +using ObjCRuntime; using UIKit; namespace Microsoft.Maui.Platform { + internal interface IContentViewAccessibility + { + bool HasAccessibleGesture { get; } + bool? IsInAccessibleTree { get; } + } + + internal interface IRefreshesContentRolesAfterMapping + { + } + public static partial class SemanticExtensions { + static readonly ConditionalWeakTable s_contentSemanticsDefaults = new(); + static readonly ConditionalWeakTable s_contentRoleDefaults = new(); + static readonly Selector s_accessibilityElementsSelector = new("accessibilityElements"); + static readonly NSString s_accessibilityElementsKey = new("accessibilityElements"); + static readonly Selector s_isAccessibilityElementSelector = new("isAccessibilityElement"); + static readonly NSString s_isAccessibilityElementKey = new("isAccessibilityElement"); + static readonly NSString s_subviewsKey = new("subviews"); + const int MaxAccessibleSubviewDepth = 32; + [ThreadStatic] + static ContentRoleRefreshBatch? s_contentRoleRefreshBatch; + [ThreadStatic] + static UIView? s_mappingExplicitRole; + + internal const string ExcludedWithChildrenPropertyName = "ExcludedWithChildren"; + + [ThreadStatic] + static IElementHandler? s_roleMappingHandler; + [ThreadStatic] + static string? s_roleMappingProperty; + + internal static bool IsMappingContentRole(IElementHandler handler, string property) => + ReferenceEquals(s_roleMappingHandler, handler) && s_roleMappingProperty == property; + + internal static bool RefreshesAfterContentMapping(IElementHandler handler) => + handler is ContentViewHandler or BorderHandler or ScrollViewHandler or RefreshViewHandler or SwipeViewHandler or SwipeItemViewHandler; + + internal static void ContentMapped(IViewHandler handler) + { + // ElementHandler refreshes after app mappings; keep direct mapper calls working too. + if (!RefreshesAfterContentMapping(handler) + || (!handler.IsMappingProperties() && !IsMappingContentRole(handler, nameof(IContentView.Content)))) + ContentChanged(handler); + } + + internal static void UpdateContentRoleMapping(IPropertyMapper? mapper, IElementHandler handler, IElement view, string property) + { + var previousHandler = s_roleMappingHandler; + var previousProperty = s_roleMappingProperty; + s_roleMappingHandler = handler; + s_roleMappingProperty = property; + try + { + mapper?.UpdateProperty(handler, view, property); + } + finally + { + s_roleMappingHandler = previousHandler; + s_roleMappingProperty = previousProperty; + } + } + + internal static ContentRoleRefreshBatch? BeginContentRoleRefresh() => + s_contentRoleRefreshBatch is null ? s_contentRoleRefreshBatch = new() : null; + + internal sealed class ContentRoleRefreshBatch : IDisposable + { + HashSet? _visited; + List? _hosts; + + internal void Collect(UIView? ancestor) + { + int firstHost = _hosts?.Count ?? 0; + for (; ancestor is not null && (_visited ??= new()).Add(ancestor); ancestor = ancestor.Superview) + { + if (s_contentSemanticsDefaults.TryGetValue(ancestor, out var saved)) + { + if (saved.IsRefreshingMapper) + { + saved.NeedsRoleRefresh = true; + break; + } + (_hosts ??= new()).Add(ancestor); + } + } + + // Add new hosts outermost first; a previously visited host already has its + // ancestors ahead of it. Reversing the full list at flush gives inside-out order. + _hosts?.Reverse(firstHost, _hosts.Count - firstHost); + } + + public void Dispose() + { + s_contentRoleRefreshBatch = null; + if (_hosts is null) + return; + + // Evaluate content hosts after descendants finish mapping and attaching. + for (int i = _hosts.Count - 1; i >= 0; i--) + RefreshContentHost(_hosts[i]); + } + } + internal static void UpdateSemantics(this UIBarItem platformView, Semantics? semantics) { if (semantics == null) @@ -90,6 +197,12 @@ public static void UpdateSemantics(this UIView platformView, IView view) { var semantics = view?.Semantics; + if (view is IContentView contentView && UsesContentSemantics(platformView, view)) + { + UpdateContentSemantics(platformView, contentView, semantics); + return; + } + // Null semantics (e.g. ClearValue): reverse any previous promotion so the layout // stops announcing stale content and its children become navigable again. if (semantics is null) @@ -186,6 +299,286 @@ public static void UpdateSemantics(this UIView platformView, IView view) UpdateSemantics(platformView, semantics); } + static void UpdateContentSemantics(UIView platformView, IContentView view, Semantics? semantics) + { + var settings = view as IContentViewAccessibility; + bool? explicitRole = settings?.IsInAccessibleTree; + if (semantics is null || !HasContentSemantics(semantics)) + { + if (s_contentSemanticsDefaults.TryGetValue(platformView, out var saved)) + { + saved.Restore(platformView, explicitRole); + s_contentSemanticsDefaults.Remove(platformView); + } + + return; + } + + var defaults = s_contentSemanticsDefaults.GetValue(platformView, static native => new(native)); + defaults.SetContent(view, semantics.IsHeading); + platformView.AccessibilityLabel = semantics.Description; + platformView.AccessibilityHint = semantics.Hint; + ApplyContentRole(platformView, view, defaults); + UpdateSemanticsHeading(platformView, semantics.IsHeading || defaults.IsHeading); + } + + static void ApplyContentRole(UIView platformView, IContentView view, ContentSemanticsDefaults defaults) + { + var settings = view as IContentViewAccessibility; + bool? explicitRole = settings?.IsInAccessibleTree; + bool groupChildren = explicitRole != true && !defaults.HasSemanticHeading + && !defaults.IsAccessibilityElement && !defaults.IsHeading && settings?.HasAccessibleGesture != true + && view.PresentedContent is not null && HasAccessibleSubview(platformView, 0); + + var isElement = explicitRole ?? !groupChildren; + if (platformView.IsAccessibilityElement != isElement) + platformView.IsAccessibilityElement = isElement; + if (platformView.ShouldGroupAccessibilityChildren != groupChildren) + platformView.ShouldGroupAccessibilityChildren = groupChildren; + } + + internal static void RefreshAncestorContentRoles(UIView platformView) + { + if (ReferenceEquals(s_mappingExplicitRole, platformView) + || (s_contentSemanticsDefaults.TryGetValue(platformView, out var current) && current.IsRefreshingMapper)) + return; + + if (s_contentRoleRefreshBatch is { } batch) + { + batch.Collect(platformView.Superview); + return; + } + + // Run the effective mapper inside-out, including app appends, before visiting the next host. + for (var ancestor = platformView.Superview; ancestor is not null; ancestor = ancestor.Superview) + { + if (!RefreshContentHost(ancestor)) + return; + } + } + + static bool RefreshContentHost(UIView ancestor) + { + if (s_contentSemanticsDefaults.TryGetValue(ancestor, out var saved) + && saved.TryGetContent(out var view) + && view.Handler is IViewHandler handler + && ReferenceEquals(handler.PlatformView, ancestor) + && ReferenceEquals(handler.VirtualView, view)) + { + // The active walk will continue past this host after its mapper finishes. + if (saved.IsRefreshingMapper) + { + saved.NeedsRoleRefresh = true; + return false; + } + + saved.IsRefreshingMapper = true; + try + { + handler.UpdateValue(nameof(IView.Semantics)); + // Replay once with the final descendant state, preserving app mapper overrides. + // A mapper which repeatedly mutates the tree must not cause an endless refresh. + if (saved.NeedsRoleRefresh) + { + saved.NeedsRoleRefresh = false; + handler.UpdateValue(nameof(IView.Semantics)); + } + } + finally + { + saved.IsRefreshingMapper = false; + saved.NeedsRoleRefresh = false; + } + } + + return true; + } + + internal static bool UsesContentSemantics(UIView platformView, IView view) => + view is IContentView and not ILayout && platformView is not (UIControl or SemanticSwitchContentView); + + static bool HasContentSemantics(Semantics semantics) => + semantics.IsHeading || !string.IsNullOrWhiteSpace(semantics.Description) || !string.IsNullOrWhiteSpace(semantics.Hint); + + internal static bool RefreshContentSemantics(IViewHandler handler) + { + if (handler.VirtualView is not { } view || handler.PlatformView is not UIView platformView + || !UsesContentSemantics(platformView, view) + || !(view.Semantics is { } semantics && HasContentSemantics(semantics))) + return false; + + handler.UpdateValue(nameof(IView.Semantics)); + return true; + } + + internal static void ContentChanged(IViewHandler handler) + { + if (handler.PlatformView is UIView platformView && (!RefreshContentSemantics(handler) + || handler is not (Handlers.ElementHandler or IRefreshesContentRolesAfterMapping))) + RefreshAncestorContentRoles(platformView); + } + + internal static bool MapContentAccessibilityRole(IViewHandler handler, bool? role) + { + if (handler.VirtualView is not { } view || handler.PlatformView is not UIView platformView + || !UsesContentSemantics(platformView, view)) + return false; + + if (role.HasValue && !s_contentRoleDefaults.TryGetValue(platformView, out _)) + { + bool originalRole = s_contentSemanticsDefaults.TryGetValue(platformView, out var saved) + ? saved.IsAccessibilityElement : platformView.IsAccessibilityElement; + s_contentRoleDefaults.Add(platformView, new(originalRole)); + } + + if (!role.HasValue && s_contentRoleDefaults.TryGetValue(platformView, out var previousRole)) + { + platformView.IsAccessibilityElement = previousRole.Value; + s_contentRoleDefaults.Remove(platformView); + } + + var previousMapping = s_mappingExplicitRole; + // This Semantics update is part of the active automation mapping, not its final state. + s_mappingExplicitRole = platformView; + try + { + RefreshContentSemantics(handler); + } + finally + { + s_mappingExplicitRole = previousMapping; + } + + // A replacement Semantics mapping can map the label and hint without applying the role. + if (role.HasValue) + platformView.IsAccessibilityElement = role.Value; + + if (handler is not (Handlers.ElementHandler or IRefreshesContentRolesAfterMapping)) + RefreshAncestorContentRoles(platformView); + return true; + } + + internal static bool IsNonTransparent(IViewHandler handler, UIView platformView) => + platformView.Alpha > 0 && (handler.ContainerView is not UIView container || container.Alpha > 0); + + internal static bool IsAccessibleLeaf(IViewHandler handler, UIView view) => + view.IsAccessibilityElement && IsAccessibleBranch(view) + && (handler.ContainerView is not UIView container || ReferenceEquals(container, view) + || IsAccessibleBranch(container)); + + static bool IsAccessibleBranch(UIView view) => + !view.Hidden && view.Alpha > 0 && !view.AccessibilityElementsHidden; + + static bool HasAccessibleSubview(UIView platformView, int depth) + { + if (depth >= MaxAccessibleSubviewDepth || platformView.AccessibilityElementsHidden) + return false; + + // Even an empty explicit array replaces UIKit's subview traversal. + if (GetExplicitAccessibilityElements(platformView) is { } elements) + return HasAccessibleElement(elements, depth); + + // The typed Subviews getter marshals every child, even when the first one qualifies. + if (platformView.ValueForKey(s_subviewsKey) is NSArray subviews) + { + var count = subviews.Count; + for (nuint i = 0; i < count; i++) + { + if (subviews.GetItem(i) is { } child && HasAccessibleBranch(child, depth)) + return true; + } + + return false; + } + + foreach (var child in platformView.Subviews) + { + if (HasAccessibleBranch(child, depth)) + return true; + } + + static bool HasAccessibleBranch(UIView view, int parentDepth) => + IsAccessibleBranch(view) && (view.IsAccessibilityElement || HasAccessibleSubview(view, parentDepth + 1)); + + return false; + } + + static NSArray? GetExplicitAccessibilityElements(NSObject container) => + container.RespondsToSelector(s_accessibilityElementsSelector) + ? container.ValueForKey(s_accessibilityElementsKey) as NSArray : null; + + static bool HasAccessibleElement(NSArray elements, int depth) + { + if (depth >= MaxAccessibleSubviewDepth) + return false; + + var count = elements.Count; + for (nuint i = 0; i < count; i++) + { + var entry = elements.GetItem(i); + if (entry is UIView view) + { + if (IsAccessibleBranch(view) && (view.IsAccessibilityElement || HasAccessibleSubview(view, depth + 1))) + return true; + } + else if (entry is not null) + { + if (entry is UIAccessibilityElement element ? element.IsAccessibilityElement + : entry.RespondsToSelector(s_isAccessibilityElementSelector) + && entry.ValueForKey(s_isAccessibilityElementKey) is NSNumber { BoolValue: true }) + return true; + if (GetExplicitAccessibilityElements(entry) is { } children && HasAccessibleElement(children, depth + 1)) + return true; + } + } + + return false; + } + + sealed class ContentRoleDefault(bool value) + { + public bool Value { get; } = value; + } + + sealed class ContentSemanticsDefaults(UIView platformView) + { + WeakReference? _content; + readonly string? _label = platformView.AccessibilityLabel; + readonly string? _hint = platformView.AccessibilityHint; + readonly bool _groupsChildren = platformView.ShouldGroupAccessibilityChildren; + public bool IsAccessibilityElement { get; } = s_contentRoleDefaults.TryGetValue(platformView, out var role) + ? role.Value : platformView.IsAccessibilityElement; + public bool IsHeading { get; } = (platformView.AccessibilityTraits & UIAccessibilityTrait.Header) != 0; + + public bool HasSemanticHeading { get; private set; } + public bool IsRefreshingMapper { get; set; } + public bool NeedsRoleRefresh { get; set; } + + public void SetContent(IContentView view, bool isHeading) + { + HasSemanticHeading = isHeading; + if (_content is null) + _content = new(view); + else + _content.SetTarget(view); + } + + public bool TryGetContent([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out IContentView? view) + { + view = null; + return _content?.TryGetTarget(out view) == true; + } + + public void Restore(UIView platformView, bool? explicitRole) + { + platformView.AccessibilityLabel = _label; + platformView.AccessibilityHint = _hint; + platformView.ShouldGroupAccessibilityChildren = _groupsChildren; + platformView.IsAccessibilityElement = explicitRole ?? IsAccessibilityElement; + UpdateSemanticsHeading(platformView, IsHeading); + } + } + internal static void UpdateSemantics(this UIView platformView, Semantics? semantics) { if (semantics == null) @@ -218,12 +611,15 @@ internal static void UpdateSemantics(this UIView platformView, Semantics? semant UpdateSemanticsHeading(platformView, semantics); } - static void UpdateSemanticsHeading(UIView platformView, Semantics semantics) + static void UpdateSemanticsHeading(UIView platformView, Semantics semantics) => + UpdateSemanticsHeading(platformView, semantics.IsHeading); + + static void UpdateSemanticsHeading(UIView platformView, bool isHeading) { var accessibilityTraits = platformView.AccessibilityTraits; var hasHeader = (accessibilityTraits & UIAccessibilityTrait.Header) == UIAccessibilityTrait.Header; - if (semantics.IsHeading) + if (isHeading) { if (!hasHeader) {