using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Beam.Dynamic { public class AnchorCollectionDataProvider : IDataProvider, IDataProvider { public IBinding? Content { get; set; } public string? RelativeTo { get; set; } private string GetAbsolute(string? @base, string relative) { if (@base is null) return relative; if (@base.EndsWith('/')) @base = @base[..^1]; if (relative.StartsWith('/')) relative = relative[1..]; return @base + '/' + relative; } public string[] Get(HtmlDocument document) { if (Content is null) return []; var node = Content.Select(document); if (node is null) return []; List links = []; foreach (var child in node.Descendants()) links.Add(child.GetAttributeValue("href", "")); return links.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); } SourceLink[] IDataProvider.Get(HtmlDocument document) { var links = Get(document); if (links.Length == 0) return []; List slinks = []; foreach (var link in links) if (Uri.TryCreate(GetAbsolute(RelativeTo, link), UriKind.RelativeOrAbsolute, out _)) slinks.Add(new SourceLink(GetAbsolute(RelativeTo, link))); return slinks.ToArray(); } } }