Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions lib/PuppeteerSharp/QueryHandlers/AriaQueryHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal class AriaQueryHandler : QueryHandler
RegexOptions.Compiled);

private static readonly Regex _normalizedRegex = new(" +", RegexOptions.Compiled);
private static readonly string[] _nonElementNodeRoles = { "StaticText", "InlineTextBox" };

public AriaQueryHandler()
{
Expand All @@ -26,8 +27,12 @@ public AriaQueryHandler()

internal override async IAsyncEnumerable<IElementHandle> QueryAllAsync(IElementHandle element, string selector)
{
var elementHandle = element as ElementHandle;
var ariaSelector = ParseAriaSelector(selector);
if (element is not ElementHandle elementHandle)
{
yield break;
}

var results = await QueryAXTreeAsync(elementHandle.Realm.Environment.Client, element, ariaSelector.Name, ariaSelector.Role).ConfigureAwait(false);

foreach (var item in results)
Expand All @@ -53,16 +58,16 @@ private static async Task<IEnumerable<AXTreeNode>> QueryAXTreeAsync(CDPSession c
Role = role,
}).ConfigureAwait(false);

return nodes.Nodes.Where((node) => node?.Role?.Value?.ToObject<string>() != "StaticText");
return nodes.Nodes.Where(node =>
node?.Role?.Value?.ToObject<string>() is not null &&
!_nonElementNodeRoles.Contains(node.Role.Value.ToObject<string>()));
}

private static AriaQueryOption ParseAriaSelector(string selector)
{
static string NormalizeValue(string value) => _normalizedRegex.Replace(value, " ").Trim();

var knownAriaAttributes = new[] { "name", "role" };
AriaQueryOption queryOptions = new();
var defaultName = _ariaSelectorAttributeRegEx.Replace(selector, new MatchEvaluator((Match match) =>
var defaultName = _ariaSelectorAttributeRegEx.Replace(selector, match =>
{
var attribute = match.Groups["attribute"].Value.Trim();
if (!knownAriaAttributes.Contains(attribute))
Expand All @@ -80,14 +85,16 @@ private static AriaQueryOption ParseAriaSelector(string selector)
}

return string.Empty;
}));
});

if (!string.IsNullOrEmpty(defaultName) && string.IsNullOrEmpty(queryOptions.Name))
{
queryOptions.Name = NormalizeValue(defaultName);
}

return queryOptions;

static string NormalizeValue(string value) => _normalizedRegex.Replace(value, " ").Trim();
}
}
}