From a63deadb07ff7952651430ee56b63c83e9855c17 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 2 Nov 2026 20:22:28 +0100 Subject: [PATCH 1/9] Fixed build --- build/Build.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/build/Build.cs b/build/Build.cs index a9d2b1c..aa33819 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -52,8 +52,6 @@ class Build : FalloutBuild string Version { get; set; } - IReadOnlyCollection TargetFrameworks { get; set; } - protected override void OnBuildInitialized() { var parser = new ReleaseNotesParser(); @@ -88,11 +86,6 @@ protected override void OnBuildInitialized() Log.Information("Building version: {Version}", Version); TargetProjects = TargetLibNames.Select(name => Solution.GetProject(name).NotNull($"{name} could not be loaded!")).ToList(); - - TargetFrameworks = TargetProjects.SelectMany(project => project.GetTargetFrameworks()).Distinct().ToList(); - TargetFrameworks.NotNull("No TargetFramework(s) found to build for!"); - - Log.Information("Target Framework(s): {Frameworks}", TargetFrameworks); } Target Clean => _ => _ From 06bb5bd3f4f3374be3ed9cba77774ac7a6ba22cd Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 3 Nov 2026 16:36:09 +0100 Subject: [PATCH 2/9] Improvements for the browser with prelim packages --- AGENTS.md | 3 +- CHANGELOG.md | 1 + docs/general/04-Input.md | 18 + .../BrowserViewTests.cs | 59 + .../BrowserEngineTests.cs | 1074 ++++++++++++++++- .../AngleSharp.Browser.csproj | 10 +- .../BrowserEngine.Frames.cs | 12 +- src/AngleSharp.Browser/BrowserEngine.Input.cs | 383 +++++- .../BrowserEngine.SelectPopup.cs | 251 ++++ .../BrowserEngine.Subframes.cs | 178 +++ src/AngleSharp.Browser/BrowserEngine.cs | 7 +- src/AngleSharp.Browser/FormControls.cs | 66 +- 12 files changed, 1996 insertions(+), 66 deletions(-) create mode 100644 src/AngleSharp.Browser/BrowserEngine.SelectPopup.cs create mode 100644 src/AngleSharp.Browser/BrowserEngine.Subframes.cs diff --git a/AGENTS.md b/AGENTS.md index cddc4ba..f4f0967 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,13 +12,14 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - Frames: `BrowserEngine.PrepareFrameAsync` lays out on the event loop; `BrowserFrame.Rasterize` (raw RGBA, overscan above/below the viewport) runs on any thread, so `BrowserView` pipelines layout and raster. Each frame's hit-test map answers cursor/link lookups without the DOM; scroll-only frames reuse the last display list unless the page has fixed/sticky boxes. - Page scrolling is smooth and runs ahead of the DOM (`ScrollPosition` vs `ScrollTop`); the view shifts the last frame meanwhile and draws an overlay scrollbar. While a script keeps the page busy, `PrepareFrameAsync` repositions the last frame (DOM-free, like a compositor) instead of waiting for the event loop. A frame after document mutations only (not resources, time or hover: `_needsFullLayout`) asks `IDomHarness.UpdateFrame()` first, which keeps or patches the last frame when the changes are confined to boxes that can be laid out on their own (out-of-flow boxes, or in-flow blocks staying the same from outside). Until a page has a measured extent, scrolling is not clamped to it (the next frame clamps). - Windows: one `BrowserEngine` (browsing context, history) per window. `WindowRequested` (target=_blank, Ctrl+click) lets the host open one via `CreateWindow()`, which shares the profile data (one synchronized cookie provider, storage and cache factories) but gets its own HTTP handler; unhandled, the page navigates in place. +- Iframes: the document of each one has its own browsing context and harness (with a viewport of the iframe's size); the page's layout leaves a `DrawSubframeCommand`, and the nested frame is prepared right after it, so layouts don't nest. The page's hit-test map delegates to the nested one, and `BrowserEngine.Subframes.cs` routes pointer coordinates, hover, focus, wheel and links. All contexts of an engine share one event loop (`FrameEventLoop` scopes cancelling), as the DOM isn't thread-safe. Script isolation is enforced at the boundary in AngleSharp.Js (`OriginPolicy`, `CrossOriginWindow`): C# code here, like the renderer, sees every document, so anything acting for a script in a frame has to act in that frame's document (see `RunScript`, `FollowHyperlink`). - `src/AngleSharp.Browser.Avalonia` (NuGet package): `BrowserView` displays frames and forwards input; with just a `Source` it creates and owns an engine while attached. Inside of this namespace `Avalonia` means the namespace itself, so `using` directives for the Avalonia framework stay above the namespace declaration. - `src/Vision`: the sample app (Avalonia), not packaged. `App` hosts the windows and the user's `Models/BrowserSettings` (JSON in the app data directory), which apply to windows opened after saving. - Vision's own UI beyond the toolbar (diagnostics tab, settings, about) is HTML/CSS in `Pages/` (embedded resources), shown by a `BrowserView` with a scripting-free engine. `HtmlPage` subclasses wire the DOM with .NET event handlers via `BrowserEngine.InvokeAsync`; don't add JavaScript there. `BrowserEngine.Diagnostics` collects the current page's requests, errors and console output. - `src/AngleSharp.Browser.Tests`: NUnit tests driving the engine headlessly. `src/AngleSharp.Browser.Avalonia.Tests`: NUnit tests of the control using Avalonia's headless platform with real Skia rendering. Don't use `Assert.ThrowsAsync` with the engine (it blocks and hangs); use an awaited try/catch. - `build/`: the Fallout build, run via `build.sh`/`build.ps1`, `.github/workflows/ci.yml` calls it. The version comes from the top of `CHANGELOG.md`; a push to `main` publishes a release, one to `devel` a pre-release. - `docs/`: the documentation, published through the doclet in `src/AngleSharp.Browser.Docs`. Keep it in sync with the public API. -- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0); remove them once fixed upstream. +- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0, `label.control` not finding wrapped controls); remove them once fixed upstream. ## Most Important Commands diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a7672..6c367a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,4 +4,5 @@ Released on Monday, November 2 2026. - Added `AngleSharp.Browser`, the UI-agnostic `BrowserEngine` for navigating, painting and interacting with pages - Added `AngleSharp.Browser.Avalonia`, the `BrowserView` control displaying web pages in Avalonia applications +- Added iframes, with their documents isolated by origin and sandbox, and input routed into them - Added `Vision`, a sample browser built on top of the control diff --git a/docs/general/04-Input.md b/docs/general/04-Input.md index 4c54c8a..829eee5 100644 --- a/docs/general/04-Input.md +++ b/docs/general/04-Input.md @@ -46,6 +46,24 @@ await engine.KeyDownAsync("Enter"); await engine.KeyUpAsync("Enter"); ``` +## Selects + +A `select` showing several options (`multiple` or `size`) is a list box: + +- A click selects a row. With `multiple`, Ctrl (or Cmd) toggles it and Shift selects the rows from the last one clicked. +- The up and down keys move the selection, with Shift (and `multiple`) extending it. +- The wheel scrolls it before the page. + +Any other `select` is a dropdown. Pressing it, or Enter, Space or Alt+Down while it has the focus, opens its list: + +- `IsSelectPopupOpen` tells if the list is open. Frames from `PrepareFrameAsync` show it on top of the page (the image of `PaintAsync` does not), so a host has nothing to do for it. It stays within the viewport, opening above the select without room below. +- While it is open, the list takes all keys: they move its highlight (skipping what is disabled), Enter, Space or Tab choose the highlighted row, and Escape closes it without a change. A click on a row chooses it. +- A press elsewhere or scrolling the page closes it. So do the select losing the focus or going away, and a change of the viewport. +- While it is closed, the up and down keys, Home, End, Page Up, Page Down and typing change the value right away. +- The list uses the color scheme of the select: dark if its `color-scheme` (or else the `color-scheme` meta element of the page) supports dark, and doesn't also support light unless `ColorScheme` is `dark`. `ColorScheme` alone doesn't make it dark, as in other browsers. Colors of the select and of its options win over those of the scheme. + +Choosing a row fires `input` and `change` if the value changed, then `click`. + ## Scrolling `ScrollAsync` scrolls by a distance: what is below the pointer, if that is a scroll container, or else the page. The returned task completes once the scrolling arrived. diff --git a/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs index c501587..712e1c4 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs @@ -3,6 +3,7 @@ using Avalonia.Controls; using Avalonia.Headless; using Avalonia.Headless.NUnit; +using Avalonia.Input; using Avalonia.Media.Imaging; using Avalonia.Platform; using Avalonia.Styling; @@ -180,6 +181,64 @@ await WaitUntil(() => window.Close(); } + [AvaloniaTest] + public async Task ClickingADropdownShowsItsListAndChoosesARow() + { + var view = new BrowserView(); + var window = Show(view); + var engine = new BrowserEngine(new BrowserOptions { IsScriptingEnabled = false }); + view.Engine = engine; + await engine.LoadHtmlAsync(""); + await WaitUntil(() => engine.HasPaintedDocument); + + // on the page, where the list goes + const int X = 280; + const int Y = 30; + await WaitUntilAsync(async () => IsRed(await GetPixelAsync(window, X, Y))); + + window.MouseDown(new global::Avalonia.Point(10, 10), MouseButton.Left); + window.MouseUp(new global::Avalonia.Point(10, 10), MouseButton.Left); + await WaitUntil(() => engine.IsSelectPopupOpen); + await WaitUntilAsync(async () => !IsRed(await GetPixelAsync(window, X, Y))); + + // the second row + window.MouseDown(new global::Avalonia.Point(10, 20 + 1 + (1.5 * 19)), MouseButton.Left); + window.MouseUp(new global::Avalonia.Point(10, 20 + 1 + (1.5 * 19)), MouseButton.Left); + await WaitUntil(() => !engine.IsSelectPopupOpen); + await WaitUntilAsync(async () => IsRed(await GetPixelAsync(window, X, Y))); + + var value = await engine.InvokeAsync(document => ((AngleSharp.Html.Dom.IHtmlSelectElement)document!.QuerySelector("select")!).Value); + Assert.That(value, Is.EqualTo("b")); + window.Close(); + engine.Dispose(); + } + + private static async Task GetPixelAsync(Window window, int x, int y) + { + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background); + using var frame = window.CaptureRenderedFrame(); + return frame is null ? new byte[4] : GetPixel(frame, x, y); + } + + private static async Task WaitUntilAsync(Func> condition) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + + while (!await condition()) + { + Assert.That(watch.ElapsedMilliseconds, Is.LessThan(10000), "Timed out."); + await Task.Delay(10); + Dispatcher.UIThread.RunJobs(); + } + } + + private static unsafe byte[] GetPixel(WriteableBitmap frame, int x, int y) + { + using var buffer = frame.Lock(); + var pixel = (byte*)buffer.Address + (y * buffer.RowBytes) + (x * 4); + return buffer.Format == PixelFormat.Bgra8888 ? [pixel[0], pixel[1], pixel[2], pixel[3]] : [pixel[2], pixel[1], pixel[0], pixel[3]]; + } + private static string CreatePage(string title, string background) => "data:text/html," + Uri.EscapeDataString($"{title}"); diff --git a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs index cd28967..0d948bb 100644 --- a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs +++ b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs @@ -1,6 +1,7 @@ namespace AngleSharp.Browser.Tests; using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; @@ -8,7 +9,9 @@ namespace AngleSharp.Browser.Tests; using AngleSharp.Css.Dom; using AngleSharp.Dom; using AngleSharp.Html.Dom; +using AngleSharp.Html.Dom.Events; using AngleSharp.Io; +using AngleSharp.Js; using NUnit.Framework; [TestFixture] @@ -40,6 +43,425 @@ public void NormalizeAddressCompletesUserInput(string input, string expected) Assert.That(BrowserEngine.NormalizeAddress(input), Is.EqualTo(expected)); } + private async Task<(IDocument Nested, IHtmlInlineFrameElement Frame)> LoadFrameAsync(string frameHtml, string pageStyle = "") + { + var srcdoc = System.Net.WebUtility.HtmlEncode(frameHtml); + await _engine.LoadHtmlAsync($""); + IHtmlInlineFrameElement frame = null!; + await _engine.InvokeAsync(document => frame = (IHtmlInlineFrameElement)document!.GetElementById("frame")!); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + await _engine.PrepareFrameAsync(); + return (frame.ContentDocument!, frame); + } + + [Test] + public async Task IframeShowsItsDocumentInItsBox() + { + await LoadFrameAsync(""); + + var frame = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(frame, 100, 100), Is.EqualTo(((byte)255, (byte)0, (byte)0))); + Assert.That(PixelOf(frame, 10, 100), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + Assert.That(PixelOf(frame, 100, 10), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + Assert.That(PixelOf(frame, 460, 100), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + } + + [Test] + public async Task IframeClipsWhatItsDocumentOverflowsWith() + { + await LoadFrameAsync("
"); + + var frame = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(frame, 100, 100), Is.EqualTo(((byte)0, (byte)255, (byte)0))); + Assert.That(PixelOf(frame, 500, 100), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + Assert.That(PixelOf(frame, 100, 300), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + } + + [Test] + public async Task IframeHasADefaultSize() + { + await _engine.LoadHtmlAsync(""); + var (width, height) = await _engine.InvokeAsync(document => + { + var box = document!.GetElementById("frame")!.GetBoundingClientRect(); + return (box.Width, box.Height); + }); + + Assert.That(width, Is.EqualTo(304)); + Assert.That(height, Is.EqualTo(154)); + } + + [Test] + public async Task ClickReachesTheElementInAnIframe() + { + var (nested, _) = await LoadFrameAsync(""); + var clicks = new List<(double X, double Y)>(); + await _engine.InvokeAsync(_ => nested.GetElementById("b")!.AddEventListener("click", (_, e) => clicks.Add((((MouseEvent)e).ClientX, ((MouseEvent)e).ClientY)))); + + await _engine.ClickAsync(50 + 30, 30 + 20); + + Assert.That(clicks, Is.EqualTo(new[] { (30d, 20d) })); + } + + [Test] + public async Task HoveringAnElementInAnIframeMatchesHoverThere() + { + var (nested, _) = await LoadFrameAsync("
"); + + await _engine.MovePointerAsync(50 + 10, 30 + 10); + var frame = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(frame, 60, 40), Is.EqualTo(((byte)255, (byte)0, (byte)0))); + } + + [Test] + public async Task TypingGoesToTheFieldInAnIframe() + { + var (nested, _) = await LoadFrameAsync(""); + + await _engine.ClickAsync(50 + 20, 30 + 10); + await _engine.TextInputAsync("Hello"); + + var value = await _engine.InvokeAsync(_ => ((IHtmlInputElement)nested.GetElementById("i")!).Value); + Assert.That(value, Is.EqualTo("Hello")); + } + + [Test] + public async Task WheelScrollsTheIframeUnderThePointer() + { + var (nested, _) = await LoadFrameAsync("
"); + + await _engine.MovePointerAsync(50 + 10, 30 + 10); + await _engine.ScrollAsync(0, 100); + + var (inner, page) = await _engine.InvokeAsync(_ => (nested.DocumentElement!.GetScrollTop(), _engine.ScrollTop)); + Assert.That(inner, Is.EqualTo(100)); + Assert.That(page, Is.EqualTo(0)); + } + + [Test] + public async Task ScrollingAnIframePaintsItsDocumentMoved() + { + await LoadFrameAsync("
"); + + await _engine.MovePointerAsync(50 + 10, 30 + 10); + await _engine.ScrollAsync(0, 100); + var frame = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(frame, 60, 30 + 10), Is.EqualTo(((byte)255, (byte)0, (byte)0))); + Assert.That(PixelOf(frame, 60, 30 + 60), Is.EqualTo(((byte)0, (byte)0, (byte)255))); + } + + [Test] + public async Task WheelMovesThePageOnceTheIframeCannotScroll() + { + var srcdoc = "short"; + await _engine.LoadHtmlAsync($"
"); + await _engine.PrepareFrameAsync(); + + await _engine.MovePointerAsync(10, 10); + await _engine.ScrollAsync(0, 100); + + await Eventually(() => _engine.ScrollPosition > 0); + } + + [Test] + public async Task ChangingTheDocumentOfAnIframeRepaintsThePage() + { + var (nested, _) = await LoadFrameAsync("
"); + await _engine.PrepareFrameAsync(); + + await _engine.InvokeAsync(_ => nested.GetElementById("d")!.SetAttribute("style", "width:100px;height:100px;background:#0000ff")); + + // the observer of the document in the iframe tells the page when the event loop gets to it + var stopwatch = Stopwatch.StartNew(); + BrowserFrame frame; + + do + { + await Task.Delay(20); + frame = await _engine.PrepareFrameAsync(); + } + while (PixelOf(frame, 60, 40) != ((byte)0, (byte)0, (byte)255) && stopwatch.ElapsedMilliseconds < 5000); + + Assert.That(PixelOf(frame, 60, 40), Is.EqualTo(((byte)0, (byte)0, (byte)255))); + } + + [Test] + public async Task LinkInAnIframeNavigatesTheIframe() + { + var page = Path.Combine(_directory, "other.html"); + File.WriteAllText(page, "other

other

"); + var address = new Uri(page).AbsoluteUri; + var (_, frame) = await LoadFrameAsync($"go"); + var url = _engine.Url; + + await _engine.ClickAsync(50 + 10, 30 + 10); + await Eventually(() => frame.ContentDocument?.Title == "other"); + + Assert.That(_engine.Url, Is.EqualTo(url)); + } + + [Test] + public async Task AnIframeGoingAwayLeavesTheTasksOfThePage() + { + var page = Path.Combine(_directory, "other.html"); + File.WriteAllText(page, "other"); + var address = new Uri(page).AbsoluteUri; + var (_, frame) = await LoadFrameAsync($"go"); + await _engine.EvaluateScriptAsync("window.ran = 0; setTimeout(function () { window.ran = 1; }, 300);"); + + await _engine.ClickAsync(50 + 10, 30 + 10); + await Eventually(() => frame.ContentDocument?.Title == "other"); + await _engine.InvokeAsync(_ => frame.ContentDocument?.Dispose()); + + var stopwatch = Stopwatch.StartNew(); + var ran = "0"; + + while (ran != "1" && stopwatch.ElapsedMilliseconds < 5000) + { + await Task.Delay(50); + ran = Convert.ToString(await _engine.EvaluateScriptAsync("window.ran"), System.Globalization.CultureInfo.InvariantCulture) ?? "0"; + } + + Assert.That(ran, Is.EqualTo("1")); + } + + [Test] + public async Task LinkWithTargetTopInAnIframeNavigatesThePage() + { + var page = Path.Combine(_directory, "other.html"); + File.WriteAllText(page, "other

other

"); + var address = new Uri(page).AbsoluteUri; + await LoadFrameAsync($"go"); + + await _engine.ClickAsync(50 + 10, 30 + 10); + + await Eventually(() => _engine.Title == "other"); + } + + /// + /// Serves pages for two origins (the same server by its address and by its name). + /// + private sealed class TwoOriginSite : IDisposable + { + private readonly System.Net.Sockets.TcpListener _listener = new(System.Net.IPAddress.Loopback, 0); + private readonly Dictionary _pages = []; + + public TwoOriginSite() + { + _listener.Start(); + _ = AcceptAsync(); + } + + private int Port => ((System.Net.IPEndPoint)_listener.LocalEndpoint).Port; + + public string PageOrigin => $"http://127.0.0.1:{Port}"; + + public string OtherOrigin => $"http://localhost:{Port}"; + + public void Add(string path, string body, string headers = "") => _pages[path] = (headers, body); + + public void Dispose() => _listener.Stop(); + + private async Task AcceptAsync() + { + try + { + while (true) + { + var client = await _listener.AcceptTcpClientAsync(); + _ = ServeAsync(client); + } + } + catch (Exception ex) when (ex is ObjectDisposedException or System.Net.Sockets.SocketException) + { + } + } + + private async Task ServeAsync(System.Net.Sockets.TcpClient client) + { + using (client) + { + var stream = client.GetStream(); + using var reader = new StreamReader(stream, leaveOpen: true); + var path = (await reader.ReadLineAsync())?.Split(' ')[1] ?? "/"; + + while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) + { + } + + var (headers, body) = _pages.GetValueOrDefault(path.Split('?')[0], (string.Empty, string.Empty)); + var content = System.Text.Encoding.UTF8.GetBytes(body); + var head = $"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {content.Length}\r\nConnection: close\r\n{headers}\r\n"; + await stream.WriteAsync(System.Text.Encoding.ASCII.GetBytes(head)); + await stream.WriteAsync(content); + } + } + } + + private async Task<(IDocument Page, IHtmlInlineFrameElement Frame)> LoadTwoOriginsAsync(TwoOriginSite site, string frameAttributes, string frameAddress) + { + site.Add("/page", $""); + await _engine.NavigateAsync(site.PageOrigin + "/page"); + IDocument page = null!; + IHtmlInlineFrameElement frame = null!; + await _engine.InvokeAsync(document => + { + page = document!; + frame = (IHtmlInlineFrameElement)document!.GetElementById("frame")!; + }); + return (page, frame); + } + + private async Task EvalInAsync(IDocument document, string script) => + await _engine.InvokeAsync(_ => Convert.ToString(document.ExecuteScript(script), System.Globalization.CultureInfo.InvariantCulture)); + + [Test] + public async Task PageCannotReachAFrameOfAnotherOrigin() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "secret"); + var (_, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + Assert.That(Convert.ToString(await _engine.EvaluateScriptAsync("String(document.getElementById('frame').contentDocument)")), Is.EqualTo("null")); + Assert.That(Convert.ToString(await _engine.EvaluateScriptAsync("typeof document.getElementById('frame').contentWindow.document")), Is.EqualTo("undefined")); + } + + [Test] + public async Task FrameOfAnotherOriginCannotReachThePage() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "frame"); + var (_, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + Assert.That(await EvalInAsync(frame.ContentDocument!, "typeof parent.document"), Is.EqualTo("undefined")); + Assert.That(await EvalInAsync(frame.ContentDocument!, "typeof top.document"), Is.EqualTo("undefined")); + } + + [Test] + public async Task FrameOfTheSameOriginCanReachThePage() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "frame"); + var (_, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.PageOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + Assert.That(await EvalInAsync(frame.ContentDocument!, "typeof parent.document"), Is.EqualTo("object")); + } + + [Test] + public async Task EngineStillSeesAndPaintsAFrameOfAnotherOrigin() + { + using var site = new TwoOriginSite(); + site.Add("/frame", ""); + var (_, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + var painted = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(painted, 100, 100), Is.EqualTo(((byte)255, (byte)0, (byte)0))); + } + + [Test] + public async Task MessageCrossesBetweenOrigins() + { + using var site = new TwoOriginSite(); + site.Add("/frame", ""); + var (page, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + await EvalInAsync(page, "window.addEventListener('message', function (e) { window.reply = e.data + '|' + e.origin; }); document.getElementById('frame').contentWindow.postMessage({ text: 'hi' }, '*')"); + + var stopwatch = Stopwatch.StartNew(); + string? reply = "undefined"; + + while (reply == "undefined" && stopwatch.ElapsedMilliseconds < 5000) + { + await Task.Delay(20); + reply = await EvalInAsync(page, "String(window.reply)"); + } + + Assert.That(reply, Is.EqualTo("back|" + site.OtherOrigin)); + Assert.That(await EvalInAsync(frame.ContentDocument!, "window.seen"), Is.EqualTo("hi|" + site.PageOrigin)); + } + + [TestCase("X-Frame-Options: DENY\r\n")] + [TestCase("X-Frame-Options: SAMEORIGIN\r\n")] + [TestCase("Content-Security-Policy: frame-ancestors 'none'\r\n")] + public async Task FrameRefusingToBeShownStaysEmpty(string headers) + { + using var site = new TwoOriginSite(); + site.Add("/frame", "", headers); + var (_, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Task.Delay(200); + + var painted = await _engine.PrepareFrameAsync(); + + Assert.That(frame.ContentDocument, Is.Null); + Assert.That(PixelOf(painted, 100, 100), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + } + + [Test] + public async Task SandboxedFrameRunsNoScripts() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "start"); + var (_, frame) = await LoadTwoOriginsAsync(site, "sandbox", site.PageOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + var title = await _engine.InvokeAsync(_ => frame.ContentDocument!.Title); + + Assert.That(title, Is.EqualTo("start")); + } + + [Test] + public async Task SandboxedFrameOfTheSameAddressIsOfAnotherOrigin() + { + using var site = new TwoOriginSite(); + site.Add("/frame", ""); + var (_, frame) = await LoadTwoOriginsAsync(site, "sandbox=\"allow-scripts\"", site.PageOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + + Assert.That(await EvalInAsync(frame.ContentDocument!, "window.seen"), Is.EqualTo("undefined")); + } + + [Test] + public async Task SandboxedFrameCannotNavigateThePage() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "go"); + site.Add("/other", "other"); + var (page, frame) = await LoadTwoOriginsAsync(site, "sandbox", site.PageOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + await _engine.PrepareFrameAsync(); + + await _engine.ClickAsync(10, 10); + await Task.Delay(200); + + Assert.That(_engine.Title, Is.Not.EqualTo("other")); + Assert.That(_engine.Url, Is.EqualTo(site.PageOrigin + "/page")); + } + + [Test] + public async Task JavaScriptLinkInAFrameRunsInTheFrame() + { + using var site = new TwoOriginSite(); + site.Add("/frame", "go"); + var (page, frame) = await LoadTwoOriginsAsync(site, string.Empty, site.OtherOrigin + "/frame"); + await Eventually(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + await _engine.PrepareFrameAsync(); + + await _engine.ClickAsync(10, 10); + + Assert.That(await EvalInAsync(frame.ContentDocument!, "String(window.ranHere)"), Is.EqualTo("1")); + Assert.That(await EvalInAsync(page, "String(window.ranHere)"), Is.EqualTo("undefined")); + } + [Test] public async Task PaintProducesImageOfViewportSize() { @@ -169,6 +591,656 @@ public async Task ClickingCheckboxLabelTogglesIt() Assert.That(check.HasAttribute("checked"), Is.True); } + [Test] + public async Task ClickingTheTextOfAWrappingLabelTogglesItsControl() + { + await _engine.LoadHtmlAsync(""); + var check = (IHtmlInputElement)_engine.Document!.GetElementById("check")!; + + var (x, y) = CenterOf("text"); + await _engine.ClickAsync(x, y); + + Assert.That(check.IsChecked, Is.True); + } + + [Test] + public async Task ClickingALabelWithAForAttributeOnlyTogglesTheNamedControl() + { + await _engine.LoadHtmlAsync(""); + var check = (IHtmlInputElement)_engine.Document!.GetElementById("check")!; + + var (x, y) = CenterOf("text"); + await _engine.ClickAsync(x, y); + + Assert.That(check.IsChecked, Is.False); + } + + private const double ListBoxRowHeight = 17.8; + + private const string ListBoxStyle = ""; + + private async Task LoadListBoxAsync(string markup) + { + await _engine.LoadHtmlAsync(ListBoxStyle + markup); + await _engine.PrepareFrameAsync(); + return (IHtmlSelectElement)_engine.Document!.QuerySelector("select")!; + } + + private Task ClickListBoxRowAsync(int row, InputModifiers modifiers = InputModifiers.None) => + _engine.ClickAsync(10, ((row + 0.5) * ListBoxRowHeight), modifiers); + + private static string[] SelectedTexts(IHtmlSelectElement select) => + select.SelectedOptions.Select(option => option.Text).ToArray(); + + [Test] + public async Task ClickingAListBoxRowSelectsOnlyIt() + { + var select = await LoadListBoxAsync(""); + + await ClickListBoxRowAsync(0); + await ClickListBoxRowAsync(2); + + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "c" })); + Assert.That(_engine.Document!.ActiveElement, Is.EqualTo(select)); + } + + [Test] + public async Task ControlClickingAListBoxRowTogglesIt() + { + var select = await LoadListBoxAsync(""); + + await ClickListBoxRowAsync(0); + await ClickListBoxRowAsync(2, InputModifiers.Control); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "a", "c" })); + + await ClickListBoxRowAsync(0, InputModifiers.Meta); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "c" })); + } + + [Test] + public async Task ShiftClickingAListBoxRowSelectsFromTheAnchor() + { + var select = await LoadListBoxAsync(""); + + await ClickListBoxRowAsync(1); + await ClickListBoxRowAsync(3, InputModifiers.Shift); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "b", "c", "d" })); + + // the anchor stays, so the range is replaced + await ClickListBoxRowAsync(0, InputModifiers.Shift); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "a", "b" })); + } + + [Test] + public async Task ModifiersDoNotExtendASingleSelectionListBox() + { + var select = await LoadListBoxAsync(""); + + await ClickListBoxRowAsync(0); + await ClickListBoxRowAsync(2, InputModifiers.Control); + + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "c" })); + } + + [Test] + public async Task ListBoxClicksFireEventsInTheOrderOfBrowsers() + { + var select = await LoadListBoxAsync(""); + var events = new List(); + + foreach (var name in new[] { "mousedown", "input", "change", "click" }) + { + select.AddEventListener(name, (_, ev) => events.Add($"{name}@{((IElement)ev.OriginalTarget!).LocalName}")); + } + + await ClickListBoxRowAsync(0); + Assert.That(events, Is.EqualTo(new[] { "mousedown@option", "input@select", "change@select", "click@option" })); + + // nothing changes, so nothing is told + events.Clear(); + await ClickListBoxRowAsync(0); + Assert.That(events, Is.EqualTo(new[] { "mousedown@option", "click@option" })); + } + + [Test] + public async Task DisabledListBoxRowsCannotBeSelected() + { + var select = await LoadListBoxAsync(""); + var events = new List(); + select.AddEventListener("click", (_, ev) => events.Add(((IElement)ev.OriginalTarget!).LocalName)); + + // the label of a group takes clicks, but selects nothing + await ClickListBoxRowAsync(0); + Assert.That(events, Is.EqualTo(new[] { "optgroup" })); + Assert.That(SelectedTexts(select), Is.Empty); + + events.Clear(); + await ClickListBoxRowAsync(2); + await ClickListBoxRowAsync(4); + Assert.That(events, Is.Empty); + Assert.That(SelectedTexts(select), Is.Empty); + + await ClickListBoxRowAsync(1); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "a" })); + } + + [Test] + public async Task ADisabledListBoxTakesNoClicks() + { + var select = await LoadListBoxAsync(""); + + await ClickListBoxRowAsync(0); + + Assert.That(SelectedTexts(select), Is.Empty); + Assert.That(_engine.Document!.ActiveElement, Is.Not.EqualTo(select)); + } + + [Test] + public async Task PressingADisabledListBoxMovesTheFocusAway() + { + await _engine.LoadHtmlAsync(ListBoxStyle + ""); + await _engine.PrepareFrameAsync(); + var field = (IHtmlInputElement)_engine.Document!.GetElementById("field")!; + var (x, y) = CenterOf("field"); + await _engine.ClickAsync(x, y); + Assert.That(field.IsFocused, Is.True); + + await ClickListBoxRowAsync(0); + + Assert.That(field.IsFocused, Is.False); + } + + [Test] + public async Task ScrollingAListBoxPaintsTheRowsFurtherDown() + { + await LoadListBoxAsync(""); + var select = _engine.Document!.QuerySelector("select")!; + select.SetScrollTop(0); + var top = await _engine.PrepareFrameAsync(); + var unselected = PixelOf(top!, 90, 4); + + select.SetScrollTop(2 * ListBoxRowHeight); + var scrolled = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(scrolled!, 90, 4), Is.Not.EqualTo(unselected)); + } + + [Test] + public async Task AListBoxScrollsToItsSelectedOption() + { + var select = await LoadListBoxAsync(""); + + Assert.That(select.GetScrollTop(), Is.EqualTo(2 * ListBoxRowHeight).Within(0.5)); + + // what is shown first now is "c" + await ClickListBoxRowAsync(0); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "c" })); + } + + [Test] + public async Task ArrowKeysMoveAndExtendAListBoxSelection() + { + var select = await LoadListBoxAsync(""); + var changes = 0; + select.AddEventListener("change", (_, _) => changes++); + + await ClickListBoxRowAsync(0); + changes = 0; + await _engine.KeyDownAsync("ArrowDown"); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "b" })); + Assert.That(changes, Is.EqualTo(1)); + + // past the disabled one, and scrolled to it + await _engine.KeyDownAsync("ArrowDown"); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "d" })); + Assert.That(select.GetScrollTop(), Is.EqualTo(2 * ListBoxRowHeight).Within(0.5)); + + await _engine.KeyDownAsync("ArrowUp", InputModifiers.Shift); + Assert.That(SelectedTexts(select), Is.EqualTo(new[] { "b", "d" })); + } + + [Test] + public async Task TheWheelScrollsAListBoxBeforeThePage() + { + await _engine.LoadHtmlAsync(ListBoxStyle + "
"); + await _engine.PrepareFrameAsync(); + var select = (IHtmlSelectElement)_engine.Document!.QuerySelector("select")!; + await _engine.MovePointerAsync(10, 5); + await _engine.PrepareFrameAsync(); + + await _engine.ScrollAsync(0, ListBoxRowHeight); + + Assert.That(select.GetScrollTop(), Is.EqualTo(ListBoxRowHeight).Within(1)); + Assert.That(_engine.ScrollTop, Is.EqualTo(0)); + + // nothing left to scroll: the page takes it + await _engine.ScrollAsync(0, 500); + await _engine.ScrollAsync(0, 40); + Assert.That(_engine.ScrollTop, Is.GreaterThan(0)); + } + + [Test] + public async Task ASelectedListBoxRowIsPainted() + { + await LoadListBoxAsync(""); + var before = await _engine.PrepareFrameAsync(); + const int X = 90; + const int Y = 4; + var unselected = PixelOf(before!, X, Y); + + await ClickListBoxRowAsync(0); + var after = await _engine.PrepareFrameAsync(); + + Assert.That(PixelOf(after!, X, Y), Is.Not.EqualTo(unselected)); + } + + private static (byte R, byte G, byte B) PixelOf(BrowserFrame frame, int x, int y) + { + var pixels = frame.Rasterize(); + var offset = (((y + frame.OverscanTop) * pixels.Width) + x) * 4; + return (pixels.Data[offset], pixels.Data[offset + 1], pixels.Data[offset + 2]); + } + + private const string DropdownStyle = ""; + + private async Task LoadDropdownAsync(string markup) + { + await _engine.LoadHtmlAsync(DropdownStyle + markup); + await _engine.PrepareFrameAsync(); + return (IHtmlSelectElement)_engine.Document!.QuerySelector("select")!; + } + + private async Task PressKeyAsync(string key, InputModifiers modifiers = InputModifiers.None) + { + await _engine.KeyDownAsync(key, modifiers); + await _engine.KeyUpAsync(key, modifiers); + } + + [Test] + public async Task ClickingADropdownOpensItAndAgainClosesIt() + { + var select = await LoadDropdownAsync(""); + + await _engine.ClickAsync(10, 10); + Assert.That(_engine.IsSelectPopupOpen, Is.True); + Assert.That(_engine.Document!.ActiveElement, Is.EqualTo(select)); + + await _engine.ClickAsync(10, 10); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + } + + [Test] + public async Task ClickingARowOfADropdownSelectsIt() + { + var select = await LoadDropdownAsync(""); + var events = new List(); + + foreach (var name in new[] { "input", "change", "click" }) + { + select.AddEventListener(name, (_, _) => events.Add(name)); + } + + await _engine.ClickAsync(10, 10); + events.Clear(); + // the rows follow below the select: the third one + await _engine.ClickAsync(10, 20 + 1 + (2.5 * PopupRowHeight)); + + Assert.That(_engine.IsSelectPopupOpen, Is.False); + Assert.That(select.Value, Is.EqualTo("c")); + Assert.That(events, Is.EqualTo(new[] { "input", "change", "click" })); + } + + // of the default font of a select: 1.2em of 13.33px and the padding of the row + private const double PopupRowHeight = 19; + + [Test] + public async Task DisabledRowsAndGroupsOfADropdownLeaveItOpen() + { + var select = await LoadDropdownAsync(""); + + await _engine.ClickAsync(10, 10); + await _engine.ClickAsync(10, 20 + 1 + (1.5 * PopupRowHeight)); + Assert.That(_engine.IsSelectPopupOpen, Is.True); + await _engine.ClickAsync(10, 20 + 1 + (2.5 * PopupRowHeight)); + Assert.That(_engine.IsSelectPopupOpen, Is.True); + Assert.That(select.Value, Is.EqualTo("a")); + + await _engine.ClickAsync(10, 20 + 1 + (3.5 * PopupRowHeight)); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + Assert.That(select.Value, Is.EqualTo("c")); + } + + [Test] + public async Task ClickingOutsideOfADropdownClosesItAndReachesThePage() + { + await LoadDropdownAsync("
"); + var clicks = 0; + _engine.Document!.GetElementById("out")!.AddEventListener("click", (_, _) => clicks++); + + await _engine.ClickAsync(10, 10); + await _engine.ClickAsync(10, 220); + + Assert.That(_engine.IsSelectPopupOpen, Is.False); + Assert.That(clicks, Is.EqualTo(1)); + Assert.That(_engine.Document!.ActiveElement, Is.Not.InstanceOf()); + } + + [Test] + public async Task ADisabledDropdownOrOnePreventedDoesNotOpen() + { + var select = await LoadDropdownAsync(""); + await _engine.ClickAsync(10, 10); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + + select = await LoadDropdownAsync(""); + select.AddEventListener("mousedown", (_, ev) => ev.Cancel()); + await _engine.ClickAsync(10, 10); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + + await LoadDropdownAsync(""); + await _engine.ClickAsync(10, 10); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + } + + [Test] + public async Task KeysMoveTheHighlightOfAnOpenDropdownUntilCommitted() + { + var select = await LoadDropdownAsync(""); + var changes = 0; + select.AddEventListener("change", (_, _) => changes++); + + await _engine.ClickAsync(10, 10); + await PressKeyAsync("ArrowDown"); + await PressKeyAsync("ArrowDown"); + Assert.That(select.Value, Is.EqualTo("a3")); + Assert.That(changes, Is.EqualTo(0)); + + // skipped what is disabled: on a4 now, then back + await PressKeyAsync("ArrowUp"); + await PressKeyAsync("Enter"); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + Assert.That(select.Value, Is.EqualTo("g0")); + Assert.That(changes, Is.EqualTo(1)); + + // Escape takes the moved highlight back + await PressKeyAsync("Enter"); + Assert.That(_engine.IsSelectPopupOpen, Is.True); + await PressKeyAsync("ArrowDown"); + await PressKeyAsync("Escape"); + Assert.That(_engine.IsSelectPopupOpen, Is.False); + Assert.That(select.Value, Is.EqualTo("g0")); + + // Tab commits and stays + await PressKeyAsync(" "); + await PressKeyAsync("End"); + await PressKeyAsync("Tab"); + Assert.That(select.Value, Is.EqualTo("a4")); + Assert.That(_engine.Document!.ActiveElement, Is.EqualTo(select)); + + await PressKeyAsync("ArrowDown", InputModifiers.Alt); + Assert.That(_engine.IsSelectPopupOpen, Is.True); + await PressKeyAsync("Escape"); + } + + [Test] + public async Task KeysChangeAClosedDropdownRightAway() + { + var select = await LoadDropdownAsync(""); + var changes = 0; + select.AddEventListener("change", (_, _) => changes++); + await _engine.ClickAsync(10, 10); + await PressKeyAsync("Escape"); + + await PressKeyAsync("ArrowDown"); + Assert.That(select.Value, Is.EqualTo("g0")); + await PressKeyAsync("ArrowDown"); + Assert.That(select.Value, Is.EqualTo("a4")); + await PressKeyAsync("ArrowUp"); + Assert.That(select.Value, Is.EqualTo("g0")); + await PressKeyAsync("End"); + Assert.That(select.Value, Is.EqualTo("a4")); + await PressKeyAsync("Home"); + Assert.That(select.Value, Is.EqualTo("a0")); + await PressKeyAsync("PageDown"); + Assert.That(select.Value, Is.EqualTo("a3")); + Assert.That(changes, Is.EqualTo(6)); + + // nowhere to go, nothing to tell + changes = 0; + await PressKeyAsync("End"); + await PressKeyAsync("ArrowDown"); + Assert.That(changes, Is.EqualTo(1)); + } + + [Test] + public async Task TypingFindsTheOptionsOfADropdown() + { + var select = await LoadDropdownAsync(""); + await _engine.ClickAsync(10, 10); + await PressKeyAsync("Escape"); + + // goes through the ones starting with a repeated letter + await PressKeyAsync("a"); + Assert.That(select.Value, Is.EqualTo("avocado")); + await PressKeyAsync("a"); + Assert.That(select.Value, Is.EqualTo("apricot")); + await Task.Delay(1100); + + // further letters narrow it down; nothing matching changes nothing + await PressKeyAsync("c"); + Assert.That(select.Value, Is.EqualTo("cherry")); + await PressKeyAsync("h"); + Assert.That(select.Value, Is.EqualTo("cherry")); + await PressKeyAsync("x"); + Assert.That(select.Value, Is.EqualTo("cherry")); + await Task.Delay(1100); + + // a disabled one isn't found + await PressKeyAsync("b"); + Assert.That(select.Value, Is.EqualTo("cherry")); + } + + [Test] + public async Task TheKeysOfAnOpenDropdownAreNotForThePage() + { + var select = await LoadDropdownAsync(""); + var keys = new List(); + select.AddEventListener("keydown", (_, _) => keys.Add("keydown")); + + await _engine.ClickAsync(10, 10); + await _engine.KeyDownAsync("ArrowDown"); + + Assert.That(keys, Is.Empty); + } + + [Test] + public async Task HoveringADropdownRowHighlightsIt() + { + var select = await LoadDropdownAsync(""); + await _engine.ClickAsync(10, 10); + await _engine.PrepareFrameAsync(); + + await _engine.MovePointerAsync(10, 20 + 1 + (2.5 * PopupRowHeight)); + await PressKeyAsync("Enter"); + + Assert.That(select.Value, Is.EqualTo("c")); + } + + [Test] + public async Task AnOpenDropdownIsPaintedOnTopOfThePage() + { + await LoadDropdownAsync("
"); + const int X = 95; + const int Y = 30; + var closed = PixelOf((await _engine.PrepareFrameAsync())!, X, Y); + Assert.That(closed, Is.EqualTo(((byte)255, (byte)0, (byte)0))); + + await _engine.ClickAsync(10, 10); + var open = PixelOf((await _engine.PrepareFrameAsync())!, X, Y); + Assert.That(open, Is.Not.EqualTo(closed)); + + await PressKeyAsync("Escape"); + Assert.That(PixelOf((await _engine.PrepareFrameAsync())!, X, Y), Is.EqualTo(closed)); + } + + [TestCase("", null, 255)] + [TestCase("", "dark", 255)] + [TestCase("", "light", 59)] + [TestCase("", "dark", 59)] + [TestCase("", "light", 255)] + [TestCase("", "light", 59)] + [TestCase("", "dark", 255)] + public async Task AnOpenDropdownUsesTheColorSchemeOfThePage(string head, string? preference, int expected) + { + _engine.ColorScheme = preference; + await LoadDropdownAsync(head + ""); + + await _engine.ClickAsync(10, 10); + // the end of the first row, which isn't the highlighted one + var frame = await _engine.PrepareFrameAsync(); + await PressKeyAsync("ArrowDown"); + frame = await _engine.PrepareFrameAsync(); + + Assert.That((int)PixelOf(frame!, 90, 20 + 1 + 5).R, Is.EqualTo(expected)); + _engine.ColorScheme = null; + } + + [Test] + public async Task ControlsDoNotTakeTheTextColorOfThePage() + { + var select = await LoadDropdownAsync(""); + + Assert.That(select.ComputeCurrentStyle().GetPropertyValue("color"), Is.EqualTo("rgba(0, 0, 0, 1)")); + } + + [Test] + public async Task ClicksHitAnAbsoluteBoxWhereItIsPlacedAgainstTheViewport() + { + await _engine.LoadHtmlAsync("
"); + await _engine.PrepareFrameAsync(); + var clicks = 0; + _engine.Document!.GetElementById("b")!.AddEventListener("click", (_, _) => clicks++); + + await _engine.ClickAsync(10, 10); + + Assert.That(clicks, Is.EqualTo(1)); + } + + [Test] + public async Task ClicksReachWhatEscapesAClipAndWhatIsInLaterColumns() + { + await _engine.LoadHtmlAsync(""" + +
+
+
+ +
+ + """); + await _engine.PrepareFrameAsync(); + var clicks = new List(); + _engine.Document!.GetElementById("escaped")!.AddEventListener("click", (_, _) => clicks.Add("escaped")); + _engine.Document!.GetElementById("column")!.AddEventListener("click", (_, _) => clicks.Add("column")); + + await _engine.ClickAsync(210, 10); + var column = _engine.Document!.GetElementById("column")!.GetBoundingClientRect(); + Assert.That(column.Left, Is.EqualTo(210)); + await _engine.ClickAsync(column.Left + 10, column.Top + 10); + + Assert.That(clicks, Is.EqualTo(new[] { "escaped", "column" })); + } + + [Test] + public async Task ClientRectsCanBeIndexedByScripts() + { + await _engine.LoadHtmlAsync("
"); + + var width = await _engine.EvaluateScriptAsync("document.getElementById('box').getClientRects()[0].width"); + + Assert.That(Convert.ToDouble(width), Is.EqualTo(30)); + } + + [Test] + public async Task OpeningADropdownAsksForAFrame() + { + await LoadDropdownAsync(""); + await _engine.PrepareFrameAsync(); + var invalidated = 0; + _engine.Invalidated += (_, _) => invalidated++; + + await _engine.ClickAsync(10, 10); + + Assert.That(invalidated, Is.GreaterThan(0)); + Assert.That((await _engine.PrepareFrameAsync())!.Width, Is.GreaterThan(0)); + } + + [Test] + public async Task ThePopupOfADropdownOpensAboveWithoutRoomBelow() + { + await _engine.LoadHtmlAsync(DropdownStyle + "
"); + await _engine.PrepareFrameAsync(); + var select = (IHtmlSelectElement)_engine.Document!.QuerySelector("select")!; + var top = select.GetBoundingClientRect().Top; + + await _engine.ClickAsync(10, top + 5); + // the first row is above the select now + await _engine.ClickAsync(10, top - (3.5 * PopupRowHeight) - 1); + + Assert.That(select.Value, Is.EqualTo("a")); + } + + [Test] + public async Task ScrollingThePageClosesADropdownButTheWheelOnItsListDoesNot() + { + var options = string.Concat(Enumerable.Range(0, 40).Select(i => $"