diff --git a/.csharpierrc.json b/.csharpierrc.json new file mode 100644 index 000000000..963354f23 --- /dev/null +++ b/.csharpierrc.json @@ -0,0 +1,3 @@ +{ + "printWidth": 120 +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..85a5dc183 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Commits that only reformat code. `git blame` skips them when run with +# `git config blame.ignoreRevsFile .git-blame-ignore-revs`. GitHub skips them already. + +# Format codebase with CSharpier +eaacd7b0a690886a276bb48409e6a715ddff5e33 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc36856bd..9c6a9f2df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,26 @@ permissions: contents: read jobs: + csharpier: + name: csharpier + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 10.0.x + 11.0.x + + - name: Restore tools + run: dotnet tool restore + + - name: Check formatting + run: dotnet csharpier check . + build: name: restore-build-test runs-on: ubuntu-latest @@ -28,8 +48,12 @@ jobs: - name: Restore run: dotnet restore E2E.slnx + # CSharpier owns whitespace and layout (see the csharpier job), so `dotnet format` checks only code style and + # analyzers. Its whitespace pass would undo CSharpier's layout. - name: Format - run: dotnet format E2E.slnx --verify-no-changes --no-restore + run: | + dotnet format style E2E.slnx --verify-no-changes --no-restore + dotnet format analyzers E2E.slnx --verify-no-changes --no-restore - name: Build run: dotnet build E2E.slnx --no-restore -c Release diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100755 index 000000000..3af48fa0a --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +dotnet husky run --group pre-push diff --git a/.husky/task-runner.json b/.husky/task-runner.json new file mode 100644 index 000000000..d9680b7dd --- /dev/null +++ b/.husky/task-runner.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://alirezanet.github.io/Husky.Net/schema.json", + "tasks": [ + { + "name": "csharpier-check", + "group": "pre-push", + "command": "dotnet", + "args": ["csharpier", "check", "."] + } + ] +} diff --git a/CLAUDE.md b/CLAUDE.md index c3f4007f6..181ac7ab7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,6 +30,7 @@ This repo is a .NET port of [tester-army/e2e](https://github.com/tester-army/e2e ## Before you push +- CSharpier owns formatting. Run `dotnet csharpier format .` from the repo root before every commit/push. The Husky.Net pre-push hook runs `dotnet csharpier check .` and blocks unformatted pushes. Do not run `dotnet format whitespace` or a plain `dotnet format`, because their whitespace pass fights CSharpier. Use `dotnet format style` / `dotnet format analyzers` only. - If the change can affect the agent, run every real-model test: `dotnet test E2E.slnx --filter "TestCategory=RealModel"`. This covers the agent, prompts, cache, replay, the web engine, and the page script. Doc-only and config-only changes skip this step. - The tests use the GitHub Copilot login (`dotnet run --project src/E2E.Cli -- login github-copilot`). If you cannot log in, say so in your report. Do not skip the tests silently. - Real-model tests can be flaky. Rerun a failed test once. If it fails twice, treat it as a real failure and report it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bee092040..1576065e1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,6 +59,12 @@ dotnet test Style is enforced at build time through `.editorconfig` and `Directory.Build.props` (`EnforceCodeStyleInBuild`, `TreatWarningsAsErrors`). C# files use the Apache file header. +[CSharpier](https://csharpier.com/) formats C# and the MSBuild files. It is a local tool in `dotnet-tools.json`, with its settings in `.csharpierrc.json`. Run `dotnet csharpier format .` before you commit. CI runs `dotnet csharpier check .` and fails on unformatted files. `dotnet format` in CI checks only code style and analyzers, because CSharpier owns the whitespace. + +A [Husky.Net](https://alirezanet.github.io/Husky.Net/) `pre-push` hook runs `dotnet csharpier check .` and stops the push if a file is not formatted. The hook installs itself: restoring or building `src/E2E` runs `dotnet tool restore` and `dotnet husky install`. This step is skipped in CI (`CI=true`), outside a git checkout, and when `HUSKY=0` is set. To install the hook by hand, run `dotnet tool restore` and then `dotnet husky install`. + +The commit that first formatted the codebase is listed in `.git-blame-ignore-revs`. Run `git config blame.ignoreRevsFile .git-blame-ignore-revs` once so `git blame` skips it. GitHub skips it already. + Do not commit API keys. ## Documentation diff --git a/apps/WebBenchmark.E2ETests/CanvasWhiteboard/CanvasWhiteboardTests.cs b/apps/WebBenchmark.E2ETests/CanvasWhiteboard/CanvasWhiteboardTests.cs index 07f065297..c17261785 100644 --- a/apps/WebBenchmark.E2ETests/CanvasWhiteboard/CanvasWhiteboardTests.cs +++ b/apps/WebBenchmark.E2ETests/CanvasWhiteboard/CanvasWhiteboardTests.cs @@ -42,18 +42,22 @@ public async Task Drags_both_shapes_into_their_slots_and_saves() Assert.That(await PixelAt(Browser, RectSlot), Is.EqualTo(White)); Assert.That(await PixelAt(Browser, CircleSlot), Is.EqualTo(White)); - await Screen.SwipeAsync(new SwipePathOptions - { - From = await OnCanvas(Browser, CanvasSize, RectHome), - To = await OnCanvas(Browser, CanvasSize, RectSlot), - }); + await Screen.SwipeAsync( + new SwipePathOptions + { + From = await OnCanvas(Browser, CanvasSize, RectHome), + To = await OnCanvas(Browser, CanvasSize, RectSlot), + } + ); await Expect.Poll(() => PixelAt(Browser, RectSlot)).ToMatchAsync(Is.EqualTo(Blue)); - await Screen.SwipeAsync(new SwipePathOptions - { - From = await OnCanvas(Browser, CanvasSize, CircleHome), - To = await OnCanvas(Browser, CanvasSize, CircleSlot), - }); + await Screen.SwipeAsync( + new SwipePathOptions + { + From = await OnCanvas(Browser, CanvasSize, CircleHome), + To = await OnCanvas(Browser, CanvasSize, CircleSlot), + } + ); await Expect.Poll(() => PixelAt(Browser, CircleSlot)).ToMatchAsync(Is.EqualTo(Orange)); await Expect.Poll(() => PixelAt(Browser, SaveButtonEdge)).ToMatchAsync(Is.EqualTo(Blue)); @@ -65,11 +69,13 @@ await Screen.SwipeAsync(new SwipePathOptions [Test] public async Task Bounces_a_shape_off_the_wrong_slot_and_refuses_to_save_early() { - await Screen.SwipeAsync(new SwipePathOptions - { - From = await OnCanvas(Browser, CanvasSize, RectHome), - To = await OnCanvas(Browser, CanvasSize, CircleSlot), - }); + await Screen.SwipeAsync( + new SwipePathOptions + { + From = await OnCanvas(Browser, CanvasSize, RectHome), + To = await OnCanvas(Browser, CanvasSize, CircleSlot), + } + ); await Expect.Poll(() => CountColor(Browser, BannerBand, Red)).ToMatchAsync(Is.GreaterThan(0)); Assert.That(await PixelAt(Browser, RectHome), Is.EqualTo(Blue)); Assert.That(await PixelAt(Browser, CircleSlot), Is.EqualTo(White)); diff --git a/apps/WebBenchmark.E2ETests/CheckoutReview/CheckoutReviewTests.cs b/apps/WebBenchmark.E2ETests/CheckoutReview/CheckoutReviewTests.cs index 99962299d..0fd9e9e8e 100644 --- a/apps/WebBenchmark.E2ETests/CheckoutReview/CheckoutReviewTests.cs +++ b/apps/WebBenchmark.E2ETests/CheckoutReview/CheckoutReviewTests.cs @@ -14,9 +14,13 @@ public sealed class CheckoutReviewTests : BenchmarkTest public async Task Shows_a_raw_greeting_token_and_an_undefined_delivery_date_planted_bug_yet_places_the_order() { await App.OpenAsync("/e/checkout-review"); - await Expect.That(Screen.GetByTestId("checkout-greeting")).ToHaveTextAsync("Thanks, {{firstName}}! Review your order below."); + await Expect + .That(Screen.GetByTestId("checkout-greeting")) + .ToHaveTextAsync("Thanks, {{firstName}}! Review your order below."); await Expect.That(Screen.GetByTestId("delivery-estimate")).ToHaveTextAsync("Delivery: Arrives by undefined"); - await Expect.That(Screen.GetByTestId("order-lines").GetByRole("listitem")).ToContainTextAsync(["Gooseneck Kettle x1", "Single Origin Beans 1kg x2"]); + await Expect + .That(Screen.GetByTestId("order-lines").GetByRole("listitem")) + .ToContainTextAsync(["Gooseneck Kettle x1", "Single Origin Beans 1kg x2"]); await Expect.That(Screen.GetByText("Ship to: 221B Baker Street, London")).ToBeVisibleAsync(); await Screen.GetByRole("button", "Place order - $123.00").TapAsync(); diff --git a/apps/WebBenchmark.E2ETests/ContextMenuTrap/ContextMenuTrapTests.cs b/apps/WebBenchmark.E2ETests/ContextMenuTrap/ContextMenuTrapTests.cs index 576b41226..4036e243f 100644 --- a/apps/WebBenchmark.E2ETests/ContextMenuTrap/ContextMenuTrapTests.cs +++ b/apps/WebBenchmark.E2ETests/ContextMenuTrap/ContextMenuTrapTests.cs @@ -38,7 +38,9 @@ public async Task The_decoy_menu_items_refuse_and_keep_the_file() var more = Screen.GetByRole("button", "More actions for report.pdf"); await more.TapAsync(); await Screen.GetByRole("button", "Duplicate").TapAsync(); - await Expect.That(Screen.GetByTestId("notice-message")).ToHaveTextAsync("Duplicating is disabled for sample files"); + await Expect + .That(Screen.GetByTestId("notice-message")) + .ToHaveTextAsync("Duplicating is disabled for sample files"); await more.TapAsync(); await Screen.GetByRole("button", "Delete").TapAsync(); diff --git a/apps/WebBenchmark.E2ETests/ControlInventory/ControlInventoryTests.cs b/apps/WebBenchmark.E2ETests/ControlInventory/ControlInventoryTests.cs index f4f188c35..91f0959e7 100644 --- a/apps/WebBenchmark.E2ETests/ControlInventory/ControlInventoryTests.cs +++ b/apps/WebBenchmark.E2ETests/ControlInventory/ControlInventoryTests.cs @@ -56,7 +56,9 @@ public async Task The_file_menu_opens_on_right_click_only_and_Rename_renames_the { var row = Screen.GetByText("report.pdf"); await row.TapAsync(); - await Expect.That(Screen.GetByLabel("File state")).ToHaveTextAsync("a click selects nothing; the menu opens on right-click"); + await Expect + .That(Screen.GetByLabel("File state")) + .ToHaveTextAsync("a click selects nothing; the menu opens on right-click"); await row.SecondaryTapAsync(); await Expect.That(Screen.GetByLabel("File state")).ToHaveTextAsync("menu open for report.pdf"); await Screen.GetByRole("menuitem", "Rename").TapAsync(); @@ -96,7 +98,9 @@ public async Task Every_exercise_done_shows_the_success_message() await Screen.GetByLabel("Agree to terms").CheckAsync(); await Screen.GetByRole("radio", "Medium").CheckAsync(); await Screen.GetByRole("radio", "Express").CheckAsync(); - await Screen.GetByRole("button", "Hold me").LongPressAsync(new LongPressOptions { Duration = TimeSpan.FromMilliseconds(700) }); + await Screen + .GetByRole("button", "Hold me") + .LongPressAsync(new LongPressOptions { Duration = TimeSpan.FromMilliseconds(700) }); await Screen.GetByRole("button", "Double-click me").DoubleTapAsync(); await Screen.GetByText("report.pdf").SecondaryTapAsync(); await Screen.GetByRole("menuitem", "Rename").TapAsync(); diff --git a/apps/WebBenchmark.E2ETests/DatePicker/DatePickerTests.cs b/apps/WebBenchmark.E2ETests/DatePicker/DatePickerTests.cs index 927b946dd..c5690299c 100644 --- a/apps/WebBenchmark.E2ETests/DatePicker/DatePickerTests.cs +++ b/apps/WebBenchmark.E2ETests/DatePicker/DatePickerTests.cs @@ -30,7 +30,9 @@ public async Task Navigates_three_months_ahead_and_books_the_required_date() await Expect.That(dateInput).ToHaveValueAsync("2026-09-17"); await Screen.GetByRole("button", "Confirm booking").TapAsync(); - await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Appointment booked for September 17, 2026"); + await Expect + .That(Screen.GetByTestId("success-message")) + .ToHaveTextAsync("Appointment booked for September 17, 2026"); } [Test] diff --git a/apps/WebBenchmark.E2ETests/DeferredDialog/DeferredDialogTests.cs b/apps/WebBenchmark.E2ETests/DeferredDialog/DeferredDialogTests.cs index b189dcec2..7af8c1acd 100644 --- a/apps/WebBenchmark.E2ETests/DeferredDialog/DeferredDialogTests.cs +++ b/apps/WebBenchmark.E2ETests/DeferredDialog/DeferredDialogTests.cs @@ -22,7 +22,9 @@ public async Task One_submit_opens_one_confirm_even_when_double_clicked() try { await Screen.GetByRole("button", "Submit report").DoubleTapAsync(); - await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Report submitted after deferred confirmation"); + await Expect + .That(Screen.GetByTestId("success-message")) + .ToHaveTextAsync("Report submitted after deferred confirmation"); Assert.That(Volatile.Read(ref dialogs), Is.EqualTo(1)); } finally diff --git a/apps/WebBenchmark.E2ETests/Fixtures/Canvas.cs b/apps/WebBenchmark.E2ETests/Fixtures/Canvas.cs index 7b2f17ec0..b76eafb91 100644 --- a/apps/WebBenchmark.E2ETests/Fixtures/Canvas.cs +++ b/apps/WebBenchmark.E2ETests/Fixtures/Canvas.cs @@ -21,7 +21,8 @@ public static class Canvas /// Maps a point in canvas pixels to the viewport through the canvas's current box. public static async Task OnCanvas(Browser browser, Size size, Point point) { - var box = await browser.Locator("canvas").BoundingBoxAsync() ?? throw new InvalidOperationException("the canvas has no box"); + var box = await browser.Locator("canvas").BoundingBoxAsync() + ?? throw new InvalidOperationException("the canvas has no box"); return new Point(box.X + point.X * box.Width / size.Width, box.Y + point.Y * box.Height / size.Height); } @@ -35,7 +36,8 @@ public static async Task PixelAt(Browser browser, Point point) return Array.from(context.getImageData(at.x, at.y, 1, 1).data.slice(0, 3)); } """; - return await browser.EvaluateAsync(script, new { x = point.X, y = point.Y }) ?? throw new InvalidOperationException("no pixel"); + return await browser.EvaluateAsync(script, new { x = point.X, y = point.Y }) + ?? throw new InvalidOperationException("no pixel"); } /// Counts the canvas pixels painted exactly inside a canvas-space band. @@ -55,6 +57,19 @@ public static async Task CountColor(Browser browser, Band band, int[] color return count; } """; - return await browser.EvaluateAsync(script, new { band = new { x = band.X, y = band.Y, width = band.Width, height = band.Height }, color }); + return await browser.EvaluateAsync( + script, + new + { + band = new + { + x = band.X, + y = band.Y, + width = band.Width, + height = band.Height, + }, + color, + } + ); } } diff --git a/apps/WebBenchmark.E2ETests/GiftCardPurchase/GiftCardPurchaseTests.cs b/apps/WebBenchmark.E2ETests/GiftCardPurchase/GiftCardPurchaseTests.cs index 9c72f2318..f63270bdd 100644 --- a/apps/WebBenchmark.E2ETests/GiftCardPurchase/GiftCardPurchaseTests.cs +++ b/apps/WebBenchmark.E2ETests/GiftCardPurchase/GiftCardPurchaseTests.cs @@ -39,7 +39,9 @@ public async Task Sends_the_gift_card() await Expect.That(Screen.GetByTestId("total-amount")).ToHaveTextAsync("$25.00"); await Screen.GetByPlaceholder("friend@example.com").FillAsync("friend@example.com"); await Screen.GetByTestId("buy-button").TapAsync(); - await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Gift card sent to friend@example.com"); + await Expect + .That(Screen.GetByTestId("success-message")) + .ToHaveTextAsync("Gift card sent to friend@example.com"); await Expect.That(Screen.GetByText("A $25.00 gift card is on its way.")).ToBeVisibleAsync(); } } diff --git a/apps/WebBenchmark.E2ETests/ImageOnlyUi/ImageOnlyUiTests.cs b/apps/WebBenchmark.E2ETests/ImageOnlyUi/ImageOnlyUiTests.cs index 5ba10cea1..0ec99644b 100644 --- a/apps/WebBenchmark.E2ETests/ImageOnlyUi/ImageOnlyUiTests.cs +++ b/apps/WebBenchmark.E2ETests/ImageOnlyUi/ImageOnlyUiTests.cs @@ -23,7 +23,10 @@ public async Task OpenTheImageOnlyUi() public async Task The_icons_have_no_names_so_the_bare_svg_locator_is_ambiguous() { var error = await Support.FailureAsync(() => Browser.Locator("svg").TapAsync()); - Assert.That(error, Is.InstanceOf().And.Property(nameof(E2EException.Code)).EqualTo("LOCATOR_AMBIGUOUS")); + Assert.That( + error, + Is.InstanceOf().And.Property(nameof(E2EException.Code)).EqualTo("LOCATOR_AMBIGUOUS") + ); } [Test] diff --git a/apps/WebBenchmark.E2ETests/KanbanBoard/KanbanBoardTests.cs b/apps/WebBenchmark.E2ETests/KanbanBoard/KanbanBoardTests.cs index 1552316af..e015807e3 100644 --- a/apps/WebBenchmark.E2ETests/KanbanBoard/KanbanBoardTests.cs +++ b/apps/WebBenchmark.E2ETests/KanbanBoard/KanbanBoardTests.cs @@ -34,11 +34,13 @@ public async Task Pointer_drags_move_both_cards_into_the_goal_layout() [Test] public async Task A_swipe_along_a_path_drags_a_card_as_well() { - await Screen.SwipeAsync(new SwipePathOptions - { - From = await Support.CenterOfAsync(Screen.GetByTestId("card-fix-payment-bug")), - To = await Support.CenterOfAsync(Screen.GetByTestId("column-done")), - }); + await Screen.SwipeAsync( + new SwipePathOptions + { + From = await Support.CenterOfAsync(Screen.GetByTestId("card-fix-payment-bug")), + To = await Support.CenterOfAsync(Screen.GetByTestId("column-done")), + } + ); await Expect.That(Screen.GetByTestId("column-done").GetByText("Fix payment bug")).ToBeVisibleAsync(); } diff --git a/apps/WebBenchmark.E2ETests/LoginForm/LoginFormTests.cs b/apps/WebBenchmark.E2ETests/LoginForm/LoginFormTests.cs index 8ba1909e3..1b06c3bf1 100644 --- a/apps/WebBenchmark.E2ETests/LoginForm/LoginFormTests.cs +++ b/apps/WebBenchmark.E2ETests/LoginForm/LoginFormTests.cs @@ -35,7 +35,9 @@ public async Task Rejects_a_short_password() await Screen.GetByPlaceholder("Email").FillAsync(_account.Username); await Screen.GetByPlaceholder("Password").FillAsync("short"); await Screen.GetByRole("button", "Log in").TapAsync(); - await Expect.That(Screen.GetByTestId("error-message")).ToHaveTextAsync("Password must be at least 8 characters"); + await Expect + .That(Screen.GetByTestId("error-message")) + .ToHaveTextAsync("Password must be at least 8 characters"); } [Test] diff --git a/apps/WebBenchmark.E2ETests/LyingLabels/LyingLabelsTests.cs b/apps/WebBenchmark.E2ETests/LyingLabels/LyingLabelsTests.cs index dfd9c5060..2c04f1fc1 100644 --- a/apps/WebBenchmark.E2ETests/LyingLabels/LyingLabelsTests.cs +++ b/apps/WebBenchmark.E2ETests/LyingLabels/LyingLabelsTests.cs @@ -26,7 +26,10 @@ public async Task The_button_whose_accessible_name_says_Pay_now_is_the_wrong_one public async Task A_text_match_for_Pay_now_catches_the_decoy_phrase_too() { var error = await Support.FailureAsync(() => Screen.GetByText(PayNow).TapAsync()); - Assert.That(error, Is.InstanceOf().And.Property(nameof(E2EException.Code)).EqualTo("LOCATOR_AMBIGUOUS")); + Assert.That( + error, + Is.InstanceOf().And.Property(nameof(E2EException.Code)).EqualTo("LOCATOR_AMBIGUOUS") + ); await Expect.That(Screen.GetByTestId("error-message")).ToBeHiddenAsync(); } @@ -36,7 +39,8 @@ public async Task The_field_whose_accessible_name_says_Amount_is_the_wrong_one() await ButtonReading("Pay now").TapAsync(); await Screen.GetByLabel("Amount").FillAsync("42.50"); await Screen.GetByText("Submit payment").TapAsync(); - await Expect.That(Screen.GetByTestId("error-message")) + await Expect + .That(Screen.GetByTestId("error-message")) .ToHaveTextAsync("Type 42.50 into the field visibly labeled Amount, leave Reference empty"); } diff --git a/apps/WebBenchmark.E2ETests/NativeDialogs/NativeDialogsTests.cs b/apps/WebBenchmark.E2ETests/NativeDialogs/NativeDialogsTests.cs index b39438c37..ad904cb92 100644 --- a/apps/WebBenchmark.E2ETests/NativeDialogs/NativeDialogsTests.cs +++ b/apps/WebBenchmark.E2ETests/NativeDialogs/NativeDialogsTests.cs @@ -33,7 +33,10 @@ public async Task Answers_the_confirm_prompt_and_alert_chain() { await Screen.GetByRole("button", "Place order").TapAsync(); await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Order placed with code GIFT-7"); - Assert.That(seen, Is.EqualTo(new[] { "Place this order?", "Enter your gift code", "Order placed. Thank you!" })); + Assert.That( + seen, + Is.EqualTo(new[] { "Place this order?", "Enter your gift code", "Order placed. Thank you!" }) + ); } finally { diff --git a/apps/WebBenchmark.E2ETests/NewsletterSignup/NewsletterSignupTests.cs b/apps/WebBenchmark.E2ETests/NewsletterSignup/NewsletterSignupTests.cs index b5754b5c5..18e751c1f 100644 --- a/apps/WebBenchmark.E2ETests/NewsletterSignup/NewsletterSignupTests.cs +++ b/apps/WebBenchmark.E2ETests/NewsletterSignup/NewsletterSignupTests.cs @@ -21,8 +21,9 @@ public async Task Subscribe_renders_no_feedback_and_logs_a_TypeError_planted_bug await Expect.That(Screen.GetByTestId("success-message")).Not.ToBeVisibleAsync(); await Expect.That(Screen.GetByTestId("error-message")).Not.ToBeVisibleAsync(); await Expect.That(email).ToHaveValueAsync("maria.novak@example.com"); - await Expect.Poll(async () => string.Join('\n', await consoleErrors())).ToMatchAsync( - Does.Contain("Cannot read properties of undefined (reading 'subscribe')")); + await Expect + .Poll(async () => string.Join('\n', await consoleErrors())) + .ToMatchAsync(Does.Contain("Cannot read properties of undefined (reading 'subscribe')")); } /// @@ -32,7 +33,8 @@ await Expect.Poll(async () => string.Join('\n', await consoleErrors())).ToMatchA /// private async Task>> CaptureConsoleErrorsAsync() { - await Browser.EvaluateAsync(""" + await Browser.EvaluateAsync( + """ () => { const errors = []; window.e2eConsoleErrors = errors; @@ -43,7 +45,8 @@ await Browser.EvaluateAsync(""" }; return null; } - """); + """ + ); return async () => await Browser.EvaluateAsync("() => window.e2eConsoleErrors ?? []") ?? []; } } diff --git a/apps/WebBenchmark.E2ETests/OnboardingWizard/OnboardingWizardTests.cs b/apps/WebBenchmark.E2ETests/OnboardingWizard/OnboardingWizardTests.cs index 7231259b8..81c77452e 100644 --- a/apps/WebBenchmark.E2ETests/OnboardingWizard/OnboardingWizardTests.cs +++ b/apps/WebBenchmark.E2ETests/OnboardingWizard/OnboardingWizardTests.cs @@ -64,7 +64,9 @@ public async Task The_review_step_repeats_the_brief_and_finishes_with_the_PIN() await CompleteProfileAsync(); await CompletePreferencesAsync(); - await Expect.That(Screen.GetByText("Maria Novak · maria.novak@example.com · +48 601 222 333")).ToBeVisibleAsync(); + await Expect + .That(Screen.GetByText("Maria Novak · maria.novak@example.com · +48 601 222 333")) + .ToBeVisibleAsync(); await Expect.That(Screen.GetByText("Krucza 12, 00-585 Warsaw, Poland")).ToBeVisibleAsync(); await Expect.That(Screen.GetByText("Born March 14, 1990 · Product designer · 7 years")).ToBeVisibleAsync(); await Expect.That(Screen.GetByText("Plan: Studio")).ToBeVisibleAsync(); diff --git a/apps/WebBenchmark.E2ETests/OrderHistory/OrderHistoryTests.cs b/apps/WebBenchmark.E2ETests/OrderHistory/OrderHistoryTests.cs index e465f08ff..846de63ce 100644 --- a/apps/WebBenchmark.E2ETests/OrderHistory/OrderHistoryTests.cs +++ b/apps/WebBenchmark.E2ETests/OrderHistory/OrderHistoryTests.cs @@ -20,7 +20,9 @@ public async Task Overview_and_settings_render_their_panels() await Expect.That(Screen.GetByTestId("overview-panel")).ToBeHiddenAsync(); await Expect.That(Screen.GetByTestId("settings-panel")).ToContainTextAsync("Email: alex@example.com"); await Screen.GetByRole("button", "Overview").TapAsync(); - await Expect.That(Screen.GetByTestId("overview-panel")).ToContainTextAsync("You have 3 orders and 1 active subscription."); + await Expect + .That(Screen.GetByTestId("overview-panel")) + .ToContainTextAsync("You have 3 orders and 1 active subscription."); } [Test] diff --git a/apps/WebBenchmark.E2ETests/PlaybookCleanup/PlaybookCleanupTests.cs b/apps/WebBenchmark.E2ETests/PlaybookCleanup/PlaybookCleanupTests.cs index b634bfd40..851b1ff0b 100644 --- a/apps/WebBenchmark.E2ETests/PlaybookCleanup/PlaybookCleanupTests.cs +++ b/apps/WebBenchmark.E2ETests/PlaybookCleanup/PlaybookCleanupTests.cs @@ -15,7 +15,9 @@ public sealed class PlaybookCleanupTests : BenchmarkTest public async Task OpenThePlaybookCleanup() { await App.OpenAsync("/e/playbook-cleanup"); - await Expect.That(Screen.GetByRole("heading", new RoleOptions { Level = 3 })).ToHaveTextAsync(["NDA Review", Target, "Vendor Onboarding"]); + await Expect + .That(Screen.GetByRole("heading", new RoleOptions { Level = 3 })) + .ToHaveTextAsync(["NDA Review", Target, "Vendor Onboarding"]); } [Test] @@ -30,7 +32,9 @@ public async Task Deleting_the_draft_removes_it_from_an_exact_name_search() await Expect.That(dialog).ToContainTextAsync($"Are you sure you want to remove \"{Target}\"?"); await dialog.GetByRole("button", "Remove").TapAsync(); await Expect.That(dialog).ToBeHiddenAsync(); - await Expect.That(Screen.GetByRole("heading", new RoleOptions { Level = 3 })).ToHaveTextAsync(["NDA Review", "Vendor Onboarding"]); + await Expect + .That(Screen.GetByRole("heading", new RoleOptions { Level = 3 })) + .ToHaveTextAsync(["NDA Review", "Vendor Onboarding"]); await Screen.GetByLabel("Search playbooks").FillAsync(Target); await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync($"No playbooks match \"{Target}\"."); diff --git a/apps/WebBenchmark.E2ETests/PriceSorting/PriceSortingTests.cs b/apps/WebBenchmark.E2ETests/PriceSorting/PriceSortingTests.cs index 6f1ac6eaa..2c243e60d 100644 --- a/apps/WebBenchmark.E2ETests/PriceSorting/PriceSortingTests.cs +++ b/apps/WebBenchmark.E2ETests/PriceSorting/PriceSortingTests.cs @@ -17,7 +17,15 @@ public async Task Opens_in_the_featured_order_with_sale_prices_struck_through() { var rows = Screen.GetByTestId("product-list").GetByRole("listitem"); await Expect.That(rows).ToHaveCountAsync(5); - await Expect.That(rows).ToContainTextAsync(["Trail Backpack 24L", "Steel Water Bottle", "Merino Hiking Socks", "Camp Lantern", "Titanium Mug"]); + await Expect + .That(rows) + .ToContainTextAsync([ + "Trail Backpack 24L", + "Steel Water Bottle", + "Merino Hiking Socks", + "Camp Lantern", + "Titanium Mug", + ]); await Expect.That(Screen.GetByTestId("product-backpack")).ToContainTextAsync("$120.00"); await Expect.That(Screen.GetByTestId("product-backpack")).ToContainTextAsync("$49.00"); await Expect.That(Screen.GetByTestId("product-bottle")).ToHaveTextAsync("Steel Water Bottle $25.00"); @@ -31,8 +39,15 @@ public async Task Low_to_high_sorts_by_the_original_price_not_the_paid_one_plant await Expect.That(sort).ToHaveValueAsync("price-asc"); // Paid prices are socks 18, bottle 25, mug 12, lantern 54, backpack 49: a // correct sort opens with the $12 mug. The page sorts the struck prices. - await Expect.That(Screen.GetByTestId("product-list").GetByRole("listitem")).ToContainTextAsync( - ["Merino Hiking Socks", "Steel Water Bottle", "Titanium Mug", "Camp Lantern", "Trail Backpack 24L"]); + await Expect + .That(Screen.GetByTestId("product-list").GetByRole("listitem")) + .ToContainTextAsync([ + "Merino Hiking Socks", + "Steel Water Bottle", + "Titanium Mug", + "Camp Lantern", + "Trail Backpack 24L", + ]); } [Test] @@ -41,9 +56,18 @@ public async Task High_to_low_is_the_same_wrong_order_reversed_planted_bug() var sort = Screen.GetByLabel("Sort by"); await sort.SelectOptionAsync(new SelectOption { Value = "price-desc" }); await Expect.That(sort).ToHaveValueAsync("price-desc"); - await Expect.That(Screen.GetByTestId("product-list").GetByRole("listitem")).ToContainTextAsync( - ["Trail Backpack 24L", "Camp Lantern", "Titanium Mug", "Steel Water Bottle", "Merino Hiking Socks"]); + await Expect + .That(Screen.GetByTestId("product-list").GetByRole("listitem")) + .ToContainTextAsync([ + "Trail Backpack 24L", + "Camp Lantern", + "Titanium Mug", + "Steel Water Bottle", + "Merino Hiking Socks", + ]); await sort.SelectOptionAsync(new SelectOption { Value = "featured" }); - await Expect.That(Screen.GetByTestId("product-list").GetByRole("listitem").First()).ToContainTextAsync("Trail Backpack 24L"); + await Expect + .That(Screen.GetByTestId("product-list").GetByRole("listitem").First()) + .ToContainTextAsync("Trail Backpack 24L"); } } diff --git a/apps/WebBenchmark.E2ETests/ProductReviews/ProductReviewsTests.cs b/apps/WebBenchmark.E2ETests/ProductReviews/ProductReviewsTests.cs index 136c8d15a..85506ab9c 100644 --- a/apps/WebBenchmark.E2ETests/ProductReviews/ProductReviewsTests.cs +++ b/apps/WebBenchmark.E2ETests/ProductReviews/ProductReviewsTests.cs @@ -16,7 +16,9 @@ public async Task The_running_shoe_page_lists_coffee_grinder_reviews_planted_bug await App.OpenAsync("/e/product-reviews"); await Expect.That(Screen.GetByRole("heading", "Peak Trail Running Shoes")).ToBeVisibleAsync(); await Expect.That(Screen.GetByText("$139.00 - Sizes 6 to 13 - Ships in 2 days")).ToBeVisibleAsync(); - await Expect.That(Screen.GetByRole("heading", new Regex("Customer reviews"))).ToContainTextAsync("4.7 out of 5"); + await Expect + .That(Screen.GetByRole("heading", new Regex("Customer reviews"))) + .ToContainTextAsync("4.7 out of 5"); var reviews = Screen.GetByTestId("review-list").GetByRole("listitem"); await Expect.That(reviews).ToHaveCountAsync(3); diff --git a/apps/WebBenchmark.E2ETests/StaleDom/StaleDomTests.cs b/apps/WebBenchmark.E2ETests/StaleDom/StaleDomTests.cs index 570fcedd8..620cc1df7 100644 --- a/apps/WebBenchmark.E2ETests/StaleDom/StaleDomTests.cs +++ b/apps/WebBenchmark.E2ETests/StaleDom/StaleDomTests.cs @@ -38,7 +38,11 @@ public async Task Taps_the_moving_target_three_times_across_rebuilds_of_the_list private static async Task WaitForRebuildAsync(Locator target) { var before = (await target.BoundingBoxAsync())?.Y; - await Expect.Poll(async () => (await target.BoundingBoxAsync())?.Y, new PollOptions { Timeout = TimeSpan.FromSeconds(5) }) + await Expect + .Poll( + async () => (await target.BoundingBoxAsync())?.Y, + new PollOptions { Timeout = TimeSpan.FromSeconds(5) } + ) .Not.ToBeAsync(before); } } diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/ControlInventory/ControlInventoryTests.cs b/apps/WebBenchmark.E2ETests/TestsAgent/ControlInventory/ControlInventoryTests.cs index 58938a222..45bbb1ebc 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/ControlInventory/ControlInventoryTests.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/ControlInventory/ControlInventoryTests.cs @@ -32,7 +32,9 @@ public async Task Check_picks_a_radio_the_pick_replaces_with_its_summary() [Test] public async Task A_long_press_and_a_double_click_are_chosen_over_a_plain_tap() { - await Agent.ActAsync("long-press the Hold me button until its state reads long-pressed, then double-click the Double-click me button"); + await Agent.ActAsync( + "long-press the Hold me button until its state reads long-pressed, then double-click the Double-click me button" + ); await Expect.That(Screen.GetByLabel("Hold state")).ToHaveTextAsync("long-pressed"); await Expect.That(Screen.GetByLabel("Double-click state")).ToHaveTextAsync("double-clicked"); } @@ -49,7 +51,14 @@ public async Task Upload_attaches_the_named_project_files() { await Agent.ActAsync( "attach both files to the Attachments input", - new ActOptions { Params = new Dictionary { ["files"] = new[] { "Fixtures/attachment.txt", "Fixtures/second.txt" } } }); + new ActOptions + { + Params = new Dictionary + { + ["files"] = new[] { "Fixtures/attachment.txt", "Fixtures/second.txt" }, + }, + } + ); await Expect.That(Screen.GetByLabel("Attachments state")).ToHaveTextAsync("attachment.txt, second.txt"); } diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/LoginForm/LoginFormTests.cs b/apps/WebBenchmark.E2ETests/TestsAgent/LoginForm/LoginFormTests.cs index b5a2a8235..588561fdf 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/LoginForm/LoginFormTests.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/LoginForm/LoginFormTests.cs @@ -16,10 +16,17 @@ public async Task Act_signs_in_with_the_benchmark_account() { var account = Credentials.User("benchmark"); await App.OpenAsync("/e/login-form"); - await Agent.ActAsync("log in with the given credentials", new ActOptions - { - Params = new Dictionary { ["email"] = account.Username, ["password"] = account.Password }, - }); + await Agent.ActAsync( + "log in with the given credentials", + new ActOptions + { + Params = new Dictionary + { + ["email"] = account.Username, + ["password"] = account.Password, + }, + } + ); await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Logged in successfully"); } } diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/PlantedBugs/PlantedBugsTests.cs b/apps/WebBenchmark.E2ETests/TestsAgent/PlantedBugs/PlantedBugsTests.cs index 33e5ac25e..52ec727e4 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/PlantedBugs/PlantedBugsTests.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/PlantedBugs/PlantedBugsTests.cs @@ -30,7 +30,10 @@ public async Task Checkout_review_a_judgment_catches_the_broken_copy() // The Blazor page renders its content once the circuit connects, after App.OpenAsync returns, so wait for the greeting before the judge reads the screen. await Expect.That(Screen.GetByTestId("checkout-greeting")).ToBeVisibleAsync(); var caught = await CaughtTheBugAsync(() => - Agent.AssertAsync("the greeting addresses the customer by a real first name and the delivery estimate names a date")); + Agent.AssertAsync( + "the greeting addresses the customer by a real first name and the delivery estimate names a date" + ) + ); Assert.That(caught, Is.True); } diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/Scenarios/ScenariosTests.cs b/apps/WebBenchmark.E2ETests/TestsAgent/Scenarios/ScenariosTests.cs index b50475512..60da1d778 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/Scenarios/ScenariosTests.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/Scenarios/ScenariosTests.cs @@ -16,21 +16,24 @@ public Task Act_completes_shadow_dom_form() => CompleteAsync( "shadow-dom-form", "fill the form buried in the nested shadow roots and submit it to get access", - "Access granted"); + "Access granted" + ); [Test, Category("lying-labels")] public Task Act_completes_lying_labels() => CompleteAsync( "lying-labels", "send the payment; the visible text on the controls is the truth, the accessible names are not", - "Payment sent"); + "Payment sent" + ); [Test, Category("iframe-form")] public Task Act_completes_iframe_form() => CompleteAsync( "iframe-form", "read the coupon code shown in one frame and apply it through the form in the other frame", - "Coupon applied"); + "Coupon applied" + ); [Test, Category("infinite-scroll")] public Task Act_completes_infinite_scroll() => @@ -39,126 +42,140 @@ public Task Act_completes_infinite_scroll() => "infinite-scroll", "scroll the feed until the Golden Ticket loads, then claim it", "Golden Ticket claimed", - maxSteps: 60); + maxSteps: 60 + ); [Test, Category("virtualized-table")] public Task Act_completes_virtualized_table() => CompleteAsync( "virtualized-table", "scroll the windowed table until the Golden Row (row 4322) is rendered, then claim it", - "Golden Row claimed"); + "Golden Row claimed" + ); [Test, Category("overlay-trap")] public Task Act_completes_overlay_trap() => CompleteAsync( "overlay-trap", "dismiss the cookie banner and the overlay in the way, then press Continue", - "You made it past the overlay"); + "You made it past the overlay" + ); [Test, Category("sticky-chrome")] public Task Act_completes_sticky_chrome() => - CompleteAsync( - "sticky-chrome", - "scroll down to the accept button and accept the terms", - "Terms accepted"); + CompleteAsync("sticky-chrome", "scroll down to the accept button and accept the terms", "Terms accepted"); [Test, Category("async-states")] public Task Act_completes_async_states() => CompleteAsync( "async-states", "wait for the page to finish loading, read the verification code it shows, enter it, and submit once the button enables", - "Code verified successfully"); + "Code verified successfully" + ); [Test, Category("debounced-search")] public Task Act_completes_debounced_search() => CompleteAsync( "debounced-search", "search for trail mix and add exactly the item the page asks for to the cart", - "Added Trail Mix 500 g to the cart"); + "Added Trail Mix 500 g to the cart" + ); [Test, Category("hover-menu")] public Task Act_completes_hover_menu() => CompleteAsync( "hover-menu", "find Redeem voucher under the Account menu and redeem the voucher", - "Voucher redeemed"); + "Voucher redeemed" + ); [Test, Category("drag-and-drop")] public Task Act_completes_drag_and_drop() => CompleteAsync( "drag-and-drop", "drag the right items into the dropzone in the order the page asks for", - "Items dropped in the right order"); + "Items dropped in the right order" + ); [Test, Category("kanban-board")] public Task Act_completes_kanban_board() => CompleteAsync( "kanban-board", "move the cards so the board matches the goal layout the page describes, then submit the board", - "Board matches the goal"); + "Board matches the goal" + ); [Test, Category("context-menu-trap")] public Task Act_completes_context_menu_trap() => CompleteAsync( "context-menu-trap", "rename the file report.pdf to summary.pdf in the file manager", - "File renamed to summary.pdf"); + "File renamed to summary.pdf" + ); [Test, Category("stale-dom")] public Task Act_completes_stale_dom() => CompleteAsync( "stale-dom", "click the Tap me button three times; the list rebuilds itself every second", - "Target clicked 3 times"); + "Target clicked 3 times" + ); [Test, Category("otp-auto-advance")] public Task Act_completes_otp_auto_advance() => CompleteAsync( "otp-auto-advance", "enter the 6-digit code the page shows into the segmented code inputs and verify it", - "Code verified"); + "Code verified" + ); [Test, Category("date-picker")] public Task Act_completes_date_picker() => CompleteAsync( "date-picker", "book an appointment for the exact date the page requires, navigating the calendar to it", - "Appointment booked for September 17, 2026"); + "Appointment booked for September 17, 2026" + ); [Test, Category("rich-text-editor")] public Task Act_completes_rich_text_editor() => CompleteAsync( "rich-text-editor", "type \"release approved\" into the editor, make exactly the word approved bold, and check the document", - "Document approved"); + "Document approved" + ); [Test, Category("playbook-cleanup")] public Task Act_completes_playbook_cleanup() => CompleteAsync( "playbook-cleanup", "delete the playbook named \"Launch Approval Draft\", confirm the removal, then search for its exact name to verify it is gone", - "No playbooks match \"Launch Approval Draft\"."); + "No playbooks match \"Launch Approval Draft\"." + ); [Test, Category("promo-storefront")] public Task Act_completes_promo_storefront() => CompleteAsync( "promo-storefront", "buy any one product, dismissing the promotional overlays that get in the way, until the order is confirmed", - "Order confirmed"); + "Order confirmed" + ); [Test, Category("new-tab-flow")] public Task Act_completes_new_tab_flow() => CompleteAsync( "new-tab-flow", "open the verification tab, read the code it shows, then go back to the original tab, enter the code there, and verify it", - "Verified successfully"); + "Verified successfully" + ); [Test, Category("gift-card-purchase")] public Task Act_completes_gift_card_purchase() => CompleteAsync( "gift-card-purchase", "buy a gift card for friend@example.com and complete the purchase", - "Gift card sent to friend@example.com"); + "Gift card sent to friend@example.com" + ); [Test] public async Task Act_filters_the_list_and_the_URL_carries_the_filter() @@ -174,7 +191,8 @@ private async Task CompleteAsync(string slug, string goal, string success, int? await App.OpenAsync($"/e/{slug}"); await Agent.ActAsync( $"Complete this scenario as the page instructs: {goal}", - new ActOptions { MaxSteps = maxSteps }); + new ActOptions { MaxSteps = maxSteps } + ); await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync(success); } } diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/TestsAgentTest.cs b/apps/WebBenchmark.E2ETests/TestsAgent/TestsAgentTest.cs index 75ba1f34b..2a2bd8177 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/TestsAgentTest.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/TestsAgentTest.cs @@ -34,7 +34,8 @@ public abstract class TestsAgentTest : BenchmarkTest } } """, - E2EConfig.Discover().ProjectRoot); + E2EConfig.Discover().ProjectRoot + ); protected override E2EConfig Config => AgentConfig; diff --git a/apps/WebBenchmark.E2ETests/TestsAgent/UniqueCache/UniqueCacheTests.cs b/apps/WebBenchmark.E2ETests/TestsAgent/UniqueCache/UniqueCacheTests.cs index f7279a758..9c168e4cb 100644 --- a/apps/WebBenchmark.E2ETests/TestsAgent/UniqueCache/UniqueCacheTests.cs +++ b/apps/WebBenchmark.E2ETests/TestsAgent/UniqueCache/UniqueCacheTests.cs @@ -16,14 +16,17 @@ public async Task Act_adds_an_address_with_a_run_unique_label() { var label = $"Cabin {Base36(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())}"; await App.OpenAsync("/e/saved-addresses"); - await Agent.ActAsync("add a new address labelled {label} at {line}", new ActOptions - { - Params = new Dictionary + await Agent.ActAsync( + "add a new address labelled {label} at {line}", + new ActOptions { - ["label"] = Values.Unique(label), - ["line"] = "7 Pine Way, Bend", - }, - }); + Params = new Dictionary + { + ["label"] = Values.Unique(label), + ["line"] = "7 Pine Way, Bend", + }, + } + ); await Expect.That(Screen.GetByTestId("address-list")).ToContainTextAsync(label); await Expect.That(Screen.GetByTestId("toast")).ToHaveTextAsync("Address saved"); } @@ -37,8 +40,7 @@ private static string Base36(long value) { text = digits[(int)(value % 36)] + text; value /= 36; - } - while (value > 0); + } while (value > 0); return text; } } diff --git a/apps/WebBenchmark.E2ETests/VirtualizedTable/VirtualizedTableTests.cs b/apps/WebBenchmark.E2ETests/VirtualizedTable/VirtualizedTableTests.cs index b67ac75a5..0b8f9ea1f 100644 --- a/apps/WebBenchmark.E2ETests/VirtualizedTable/VirtualizedTableTests.cs +++ b/apps/WebBenchmark.E2ETests/VirtualizedTable/VirtualizedTableTests.cs @@ -34,7 +34,10 @@ public async Task Scrolls_the_windowed_table_to_the_Golden_Row_and_claims_it() await Expect.That(claim).ToBeHiddenAsync(); // The table is its own scroll container, so the table pages, not the page. - await viewport.ScrollUntilVisibleAsync(claim, new ScrollUntilVisibleOptions { Timeout = TimeSpan.FromMilliseconds(ScrollTimeoutMs) }); + await viewport.ScrollUntilVisibleAsync( + claim, + new ScrollUntilVisibleOptions { Timeout = TimeSpan.FromMilliseconds(ScrollTimeoutMs) } + ); await Expect.That(rows.Filter(hasText: "Golden Row")).ToHaveTextAsync(GoldenRowText); await Expect.That(rows.Filter(hasText: "Row 1")).ToHaveCountAsync(0); diff --git a/apps/WebBenchmark/BenchmarkApp.cs b/apps/WebBenchmark/BenchmarkApp.cs index 0a7a0df63..6ea23321d 100644 --- a/apps/WebBenchmark/BenchmarkApp.cs +++ b/apps/WebBenchmark/BenchmarkApp.cs @@ -27,13 +27,15 @@ public static class BenchmarkApp /// public static WebApplication Create(string[] args) { - var builder = WebApplication.CreateBuilder(new WebApplicationOptions - { - Args = args, - ContentRootPath = AppContext.BaseDirectory, - // The static web assets manifests are named for the app, not for the entry assembly: a test host is the entry assembly of its own run. - ApplicationName = typeof(BenchmarkApp).Assembly.GetName().Name, - }); + var builder = WebApplication.CreateBuilder( + new WebApplicationOptions + { + Args = args, + ContentRootPath = AppContext.BaseDirectory, + // The static web assets manifests are named for the app, not for the entry assembly: a test host is the entry assembly of its own run. + ApplicationName = typeof(BenchmarkApp).Assembly.GetName().Name, + } + ); // blazor.web.js comes from the framework through the manifest; outside Development the manifest is read only when asked for. StaticWebAssetsLoader.UseStaticWebAssets(builder.Environment, builder.Configuration); builder.Logging.SetMinimumLevel(LogLevel.Warning); diff --git a/apps/WebBenchmark/ExamplesCatalog.cs b/apps/WebBenchmark/ExamplesCatalog.cs index 18301a454..c73eb555c 100644 --- a/apps/WebBenchmark/ExamplesCatalog.cs +++ b/apps/WebBenchmark/ExamplesCatalog.cs @@ -22,99 +22,266 @@ public static class ExamplesCatalog { public static IReadOnlyList All { get; } = [ - new(typeof(LoginForm), "login-form", "Login Form", - "Fill credentials, handle validation errors, reach the logged-in state."), - new(typeof(ShadowDomForm), "shadow-dom-form", "Shadow DOM Form", - "Fill a form buried in nested open and closed shadow roots where CSS selectors cannot reach."), - new(typeof(CanvasOnly), "canvas-only", "Canvas Only", - "Complete a flow rendered entirely on a canvas element - no DOM, pure vision and coordinates."), - new(typeof(CanvasWhiteboard), "canvas-whiteboard", "Canvas Whiteboard", - "Drag shapes into matching slots on a Figma-style whiteboard painted entirely on one canvas, then save."), - new(typeof(DivSoup), "div-soup", "Div Soup", - "Operate a login built from bare divs with no semantic roles, labels, or test ids."), - new(typeof(AriaHiddenFlow), "aria-hidden-flow", "Aria Hidden Flow", - "Complete a plan-selection flow whose entire subtree is aria-hidden - the a11y snapshot is empty."), - new(typeof(ImageOnlyUi), "image-only-ui", "Image Only UI", - "Follow instructions rendered as images and click icon-only buttons - zero readable text in the DOM."), - new(typeof(CssContentUi), "css-content-ui", "CSS Content UI", - "Operate a flow whose every label comes from CSS pseudo-element content - the DOM is empty divs."), - new(typeof(LyingLabels), "lying-labels", "Lying Labels", - "Ignore an accessibility tree that lies - shuffled aria-labels and swapped placeholders; visible text is truth."), - new(typeof(IframeForm), "iframe-form", "Iframe Form", - "Read a code from a nested iframe and submit it through a form in another iframe."), - new(typeof(InfiniteScroll), "infinite-scroll", "Infinite Scroll", - "Scroll a paginated feed until a target item deep in the list loads, then claim it."), - new(typeof(VirtualizedTable), "virtualized-table", "Virtualized Table", - "Find a row deep in a windowed table where off-screen rows are never in the DOM."), - new(typeof(OverlayTrap), "overlay-trap", "Overlay Trap", - "Dismiss a cookie banner and an invisible click-intercepting overlay before the target button works."), - new(typeof(StickyChrome), "sticky-chrome", "Sticky Chrome", - "Scroll a far-down accept button clear of sticky header and footer chrome before clicking it."), - new(typeof(AsyncStates), "async-states", "Async States", - "Wait out a skeleton load, catch a transient toast, and submit once the button finally enables."), - new(typeof(DebouncedSearch), "debounced-search", "Debounced Search", - "Type into a debounced combobox and pick the target from a portal-rendered listbox."), - new(typeof(HoverMenu), "hover-menu", "Hover Menu", - "Navigate a hover-only nested dropdown menu to reach a buried action."), - new(typeof(ContextMenuTrap), "context-menu-trap", "Context Menu Trap", - "Rename the file report.pdf to summary.pdf in the file manager."), - new(typeof(NativeDialogs), "native-dialogs", "Native Dialogs", - "Handle a chain of native alert, confirm, and prompt dialogs to finish checkout."), - new(typeof(DeferredDialog), "deferred-dialog", "Deferred Dialog", - "Accept a confirm dialog that opens on a timer after the click has already settled."), - new(typeof(NewTabFlow), "new-tab-flow", "New Tab Flow", - "Open a second tab carrying a verification code, then return and enter it in the original tab."), - new(typeof(DragAndDrop), "drag-and-drop", "Drag and Drop", - "Drag the right items into a dropzone using pointer events in the correct order."), - new(typeof(KanbanBoard), "kanban-board", "Kanban Board", - "Move cards across a kanban board driven purely by pointer events with a drag threshold - HTML5 drag events do nothing."), - new(typeof(StaleDom), "stale-dom", "Stale DOM", - "Click a target in a list whose nodes are torn down and remounted every second - stale refs break."), - new(typeof(OtpAutoAdvance), "otp-auto-advance", "OTP Auto-Advance", - "Enter a 6-digit code into segmented inputs that auto-advance focus per digit."), - new(typeof(FileRoundTrip), "file-round-trip", "File Round Trip", - "Download a voucher file, then upload the same file back to verify its contents."), - new(typeof(FilterDeepLink), "filter-deep-link", "Filter Deep Link", - "Apply a list filter and verify the page URL carries it as a shareable query param."), - new(typeof(DatePicker), "date-picker", "Date Picker", - "Navigate a custom calendar widget across months to select an exact required date."), - new(typeof(OnboardingWizard), "onboarding-wizard", "Onboarding Wizard", - "Fill a five-step wizard from a brief only visible on step 1 - long-horizon recall across unlabeled fields, custom dropdowns, a hostile date picker, steppers, and trap toggles."), - new(typeof(RichTextEditor), "rich-text-editor", "Rich Text Editor", - "Type into a contenteditable editor and apply bold formatting to an exact phrase."), - new(typeof(PlaybookCleanup), "playbook-cleanup", "Playbook Cleanup", - "Delete 'Launch Approval Draft', confirm removal, then search for its exact name to verify it is gone."), - new(typeof(PriceSorting), "price-sorting", "Price Sorting", + new( + typeof(LoginForm), + "login-form", + "Login Form", + "Fill credentials, handle validation errors, reach the logged-in state." + ), + new( + typeof(ShadowDomForm), + "shadow-dom-form", + "Shadow DOM Form", + "Fill a form buried in nested open and closed shadow roots where CSS selectors cannot reach." + ), + new( + typeof(CanvasOnly), + "canvas-only", + "Canvas Only", + "Complete a flow rendered entirely on a canvas element - no DOM, pure vision and coordinates." + ), + new( + typeof(CanvasWhiteboard), + "canvas-whiteboard", + "Canvas Whiteboard", + "Drag shapes into matching slots on a Figma-style whiteboard painted entirely on one canvas, then save." + ), + new( + typeof(DivSoup), + "div-soup", + "Div Soup", + "Operate a login built from bare divs with no semantic roles, labels, or test ids." + ), + new( + typeof(AriaHiddenFlow), + "aria-hidden-flow", + "Aria Hidden Flow", + "Complete a plan-selection flow whose entire subtree is aria-hidden - the a11y snapshot is empty." + ), + new( + typeof(ImageOnlyUi), + "image-only-ui", + "Image Only UI", + "Follow instructions rendered as images and click icon-only buttons - zero readable text in the DOM." + ), + new( + typeof(CssContentUi), + "css-content-ui", + "CSS Content UI", + "Operate a flow whose every label comes from CSS pseudo-element content - the DOM is empty divs." + ), + new( + typeof(LyingLabels), + "lying-labels", + "Lying Labels", + "Ignore an accessibility tree that lies - shuffled aria-labels and swapped placeholders; visible text is truth." + ), + new( + typeof(IframeForm), + "iframe-form", + "Iframe Form", + "Read a code from a nested iframe and submit it through a form in another iframe." + ), + new( + typeof(InfiniteScroll), + "infinite-scroll", + "Infinite Scroll", + "Scroll a paginated feed until a target item deep in the list loads, then claim it." + ), + new( + typeof(VirtualizedTable), + "virtualized-table", + "Virtualized Table", + "Find a row deep in a windowed table where off-screen rows are never in the DOM." + ), + new( + typeof(OverlayTrap), + "overlay-trap", + "Overlay Trap", + "Dismiss a cookie banner and an invisible click-intercepting overlay before the target button works." + ), + new( + typeof(StickyChrome), + "sticky-chrome", + "Sticky Chrome", + "Scroll a far-down accept button clear of sticky header and footer chrome before clicking it." + ), + new( + typeof(AsyncStates), + "async-states", + "Async States", + "Wait out a skeleton load, catch a transient toast, and submit once the button finally enables." + ), + new( + typeof(DebouncedSearch), + "debounced-search", + "Debounced Search", + "Type into a debounced combobox and pick the target from a portal-rendered listbox." + ), + new( + typeof(HoverMenu), + "hover-menu", + "Hover Menu", + "Navigate a hover-only nested dropdown menu to reach a buried action." + ), + new( + typeof(ContextMenuTrap), + "context-menu-trap", + "Context Menu Trap", + "Rename the file report.pdf to summary.pdf in the file manager." + ), + new( + typeof(NativeDialogs), + "native-dialogs", + "Native Dialogs", + "Handle a chain of native alert, confirm, and prompt dialogs to finish checkout." + ), + new( + typeof(DeferredDialog), + "deferred-dialog", + "Deferred Dialog", + "Accept a confirm dialog that opens on a timer after the click has already settled." + ), + new( + typeof(NewTabFlow), + "new-tab-flow", + "New Tab Flow", + "Open a second tab carrying a verification code, then return and enter it in the original tab." + ), + new( + typeof(DragAndDrop), + "drag-and-drop", + "Drag and Drop", + "Drag the right items into a dropzone using pointer events in the correct order." + ), + new( + typeof(KanbanBoard), + "kanban-board", + "Kanban Board", + "Move cards across a kanban board driven purely by pointer events with a drag threshold - HTML5 drag events do nothing." + ), + new( + typeof(StaleDom), + "stale-dom", + "Stale DOM", + "Click a target in a list whose nodes are torn down and remounted every second - stale refs break." + ), + new( + typeof(OtpAutoAdvance), + "otp-auto-advance", + "OTP Auto-Advance", + "Enter a 6-digit code into segmented inputs that auto-advance focus per digit." + ), + new( + typeof(FileRoundTrip), + "file-round-trip", + "File Round Trip", + "Download a voucher file, then upload the same file back to verify its contents." + ), + new( + typeof(FilterDeepLink), + "filter-deep-link", + "Filter Deep Link", + "Apply a list filter and verify the page URL carries it as a shareable query param." + ), + new( + typeof(DatePicker), + "date-picker", + "Date Picker", + "Navigate a custom calendar widget across months to select an exact required date." + ), + new( + typeof(OnboardingWizard), + "onboarding-wizard", + "Onboarding Wizard", + "Fill a five-step wizard from a brief only visible on step 1 - long-horizon recall across unlabeled fields, custom dropdowns, a hostile date picker, steppers, and trap toggles." + ), + new( + typeof(RichTextEditor), + "rich-text-editor", + "Rich Text Editor", + "Type into a contenteditable editor and apply bold formatting to an exact phrase." + ), + new( + typeof(PlaybookCleanup), + "playbook-cleanup", + "Playbook Cleanup", + "Delete 'Launch Approval Draft', confirm removal, then search for its exact name to verify it is gone." + ), + new( + typeof(PriceSorting), + "price-sorting", + "Price Sorting", "Sort a small product grid by price and check the resulting order.", - PlantedBug: "Price sorting compares original prices instead of sale prices, so discounted products land in the wrong position (e.g. the $49 backpack sorts as $120)."), - new(typeof(CartTotals), "cart-totals", "Cart Totals", + PlantedBug: "Price sorting compares original prices instead of sale prices, so discounted products land in the wrong position (e.g. the $49 backpack sorts as $120)." + ), + new( + typeof(CartTotals), + "cart-totals", + "Cart Totals", "Adjust item quantities in a shopping cart and check the order summary math.", - PlantedBug: "The order summary is computed once from the initial quantities and never updates - changing a quantity updates the line total but subtotal and order total stay stale."), - new(typeof(CheckoutReview), "checkout-review", "Checkout Review", + PlantedBug: "The order summary is computed once from the initial quantities and never updates - changing a quantity updates the line total but subtotal and order total stay stale." + ), + new( + typeof(CheckoutReview), + "checkout-review", + "Checkout Review", "Review a prefilled order summary page and place the order.", - PlantedBug: "The greeting shows a raw {{firstName}} template token and the delivery estimate reads 'Arrives by undefined'. Placing the order still works."), - new(typeof(SavedAddresses), "saved-addresses", "Saved Addresses", + PlantedBug: "The greeting shows a raw {{firstName}} template token and the delivery estimate reads 'Arrives by undefined'. Placing the order still works." + ), + new( + typeof(SavedAddresses), + "saved-addresses", + "Saved Addresses", "Manage an address book: add a new address and remove a saved one.", - PlantedBug: "Deleting an address shows an 'Address deleted' toast but never removes the address from the list, even on retry. Adding addresses works."), - new(typeof(NewsletterSignup), "newsletter-signup", "Newsletter Signup", + PlantedBug: "Deleting an address shows an 'Address deleted' toast but never removes the address from the list, even on retry. Adding addresses works." + ), + new( + typeof(NewsletterSignup), + "newsletter-signup", + "Newsletter Signup", "Subscribe to a newsletter and confirm the signup feedback.", - PlantedBug: "The Subscribe button's handler crashes (console TypeError) and renders no confirmation or error UI - subscribing is silently impossible."), - new(typeof(OrderHistory), "order-history", "Order History", + PlantedBug: "The Subscribe button's handler crashes (console TypeError) and renders no confirmation or error UI - subscribing is silently impossible." + ), + new( + typeof(OrderHistory), + "order-history", + "Order History", "Open the account's orders section and review past orders.", - PlantedBug: "The Orders tab is stuck on 'Loading your orders...' forever while Overview and Settings work - a broken feature inside a working app (product bug, not an environment blocker)."), - new(typeof(ProductReviews), "product-reviews", "Product Reviews", + PlantedBug: "The Orders tab is stuck on 'Loading your orders...' forever while Overview and Settings work - a broken feature inside a working app (product bug, not an environment blocker)." + ), + new( + typeof(ProductReviews), + "product-reviews", + "Product Reviews", "Read a product page and its customer reviews.", - PlantedBug: "Every review on the running-shoe page is clearly about a coffee grinder - the wrong product's reviews are wired to the page."), - new(typeof(Wishlist), "wishlist", "Wishlist", + PlantedBug: "Every review on the running-shoe page is clearly about a coffee grinder - the wrong product's reviews are wired to the page." + ), + new( + typeof(Wishlist), + "wishlist", + "Wishlist", "Save products to a wishlist and check they appear on the wishlist tab.", - PlantedBug: "The wishlist tab badge counts saved items correctly, but the tab itself always renders the 'No saved items yet.' empty state - saved products are lost."), - new(typeof(PromoStorefront), "promo-storefront", "Promo Storefront", - "Browse a promo-heavy storefront, handle its overlays, and complete a purchase."), - new(typeof(GiftCardPurchase), "gift-card-purchase", "Gift Card Purchase", - "Pick a gift card amount, enter a recipient, and complete the purchase."), - new(typeof(ControlInventory), "control-inventory", "Control Inventory", - "The deterministic contract surface: plain controls with every state exposed, one exercise per agent verb. Not a hard surface."), - + PlantedBug: "The wishlist tab badge counts saved items correctly, but the tab itself always renders the 'No saved items yet.' empty state - saved products are lost." + ), + new( + typeof(PromoStorefront), + "promo-storefront", + "Promo Storefront", + "Browse a promo-heavy storefront, handle its overlays, and complete a purchase." + ), + new( + typeof(GiftCardPurchase), + "gift-card-purchase", + "Gift Card Purchase", + "Pick a gift card amount, enter a recipient, and complete the purchase." + ), + new( + typeof(ControlInventory), + "control-inventory", + "Control Inventory", + "The deterministic contract surface: plain controls with every state exposed, one exercise per agent verb. Not a hard surface." + ), ]; /// The scenario served at /e/<slug>, or null (upstream's examples.find). diff --git a/apps/WinAppBenchmark.E2ETests/Controls/ControlInventoryTests.cs b/apps/WinAppBenchmark.E2ETests/Controls/ControlInventoryTests.cs index 602f95545..012370f4b 100644 --- a/apps/WinAppBenchmark.E2ETests/Controls/ControlInventoryTests.cs +++ b/apps/WinAppBenchmark.E2ETests/Controls/ControlInventoryTests.cs @@ -18,7 +18,8 @@ public sealed class ControlInventoryTests : BenchmarkTest public async Task OpenTheInventory() => await OpenScenarioAsync("Control Inventory"); /// Shows one of the scenario's sections; every control of it fits on screen. - private async Task ShowSectionAsync(string name) => await Screen.GetByTestId($"tab-{name.ToLowerInvariant()}").TapAsync(); + private async Task ShowSectionAsync(string name) => + await Screen.GetByTestId($"tab-{name.ToLowerInvariant()}").TapAsync(); [Test] public async Task A_label_query_resolves_a_labeled_text_field() @@ -298,7 +299,9 @@ public async Task A_double_tap_lands_inside_the_300_ms_window() public async Task An_ambiguous_locator_fails_at_once() { await ShowSectionAsync("Gestures"); - var ambiguous = await Assert.ThrowsAsync(async () => await Screen.GetByTestId("fruit-row").TapAsync()); + var ambiguous = await Assert.ThrowsAsync(async () => + await Screen.GetByTestId("fruit-row").TapAsync() + ); Assert.That(ambiguous!.Code, Is.EqualTo("LOCATOR_AMBIGUOUS")); } diff --git a/apps/WinAppBenchmark.E2ETests/Fixtures/BenchmarkTest.cs b/apps/WinAppBenchmark.E2ETests/Fixtures/BenchmarkTest.cs index 7c4a46016..475fa6b15 100644 --- a/apps/WinAppBenchmark.E2ETests/Fixtures/BenchmarkTest.cs +++ b/apps/WinAppBenchmark.E2ETests/Fixtures/BenchmarkTest.cs @@ -20,8 +20,14 @@ public abstract class BenchmarkTest : WinAppTest [OneTimeSetUp] public void DeclareTheBenchmarkAccount() { - Environment.SetEnvironmentVariable("E2E_USER_BENCHMARK_USERNAME", Environment.GetEnvironmentVariable("E2E_USER_BENCHMARK_USERNAME") ?? "tester@tester.army"); - Environment.SetEnvironmentVariable("E2E_USER_BENCHMARK_PASSWORD", Environment.GetEnvironmentVariable("E2E_USER_BENCHMARK_PASSWORD") ?? "benchmark123"); + Environment.SetEnvironmentVariable( + "E2E_USER_BENCHMARK_USERNAME", + Environment.GetEnvironmentVariable("E2E_USER_BENCHMARK_USERNAME") ?? "tester@tester.army" + ); + Environment.SetEnvironmentVariable( + "E2E_USER_BENCHMARK_PASSWORD", + Environment.GetEnvironmentVariable("E2E_USER_BENCHMARK_PASSWORD") ?? "benchmark123" + ); } /// diff --git a/apps/WinAppBenchmark.E2ETests/Flows/FlowsTests.cs b/apps/WinAppBenchmark.E2ETests/Flows/FlowsTests.cs index 0ef371992..ca321e7bc 100644 --- a/apps/WinAppBenchmark.E2ETests/Flows/FlowsTests.cs +++ b/apps/WinAppBenchmark.E2ETests/Flows/FlowsTests.cs @@ -44,7 +44,15 @@ public async Task Modal_flow_confirms_through_the_native_alert() await OpenScenarioAsync("Modal Flow"); await Screen.GetByTestId("open-modal-button").TapAsync(); await Screen.GetByTestId("continue-button").TapAsync(); - await Screen.GetByRole("button", new System.Text.RegularExpressions.Regex("^confirm$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)).TapAsync(); + await Screen + .GetByRole( + "button", + new System.Text.RegularExpressions.Regex( + "^confirm$", + System.Text.RegularExpressions.RegexOptions.IgnoreCase + ) + ) + .TapAsync(); await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Flow completed"); } @@ -87,7 +95,9 @@ public async Task Choice_controls_place_the_exact_order() await Screen.GetByTestId("rush-delivery").TapAsync(); await Expect.That(Screen.GetByTestId("place-order")).ToBeEnabledAsync(); await Screen.GetByTestId("place-order").TapAsync(); - await Expect.That(Screen.GetByTestId("success-message")).ToHaveTextAsync("Order placed: Medium with Cheese, Olives (rush)"); + await Expect + .That(Screen.GetByTestId("success-message")) + .ToHaveTextAsync("Order placed: Medium with Cheese, Olives (rush)"); } // The results list is replaced by a spinner while the fetch runs, so the result row appears once it loads. diff --git a/apps/WinAppBenchmark.E2ETests/Scenarios/ScenariosTests.cs b/apps/WinAppBenchmark.E2ETests/Scenarios/ScenariosTests.cs index 4a97efc9e..9a3b14a70 100644 --- a/apps/WinAppBenchmark.E2ETests/Scenarios/ScenariosTests.cs +++ b/apps/WinAppBenchmark.E2ETests/Scenarios/ScenariosTests.cs @@ -19,12 +19,20 @@ public sealed class ScenariosTests : BenchmarkTest /// The screen's tree is hidden on purpose, so the success message never enters it: the goal tells the model the screen lists nothing and success is judged from a screenshot. /// The goal refers to the benchmark account, which comes in as params. /// Why the harness cannot finish this scenario yet. The test is declared and skipped with the reason, and turns on the day the capability lands. - public sealed record Scenario(string Name, string Goal, string Success, bool Pixels = false, bool WithAccount = false, string? Gap = null) + public sealed record Scenario( + string Name, + string Goal, + string Success, + bool Pixels = false, + bool WithAccount = false, + string? Gap = null + ) { public override string ToString() => Name; } - private const string PixelsGap = "agent.act gives the model the tree only, never a screenshot, and this screen lists nothing in the tree"; + private const string PixelsGap = + "agent.act gives the model the tree only, never a screenshot, and this screen lists nothing in the tree"; public static readonly IReadOnlyList All = [ @@ -34,26 +42,91 @@ public sealed record Scenario(string Name, string Goal, string Success, bool Pix new("Infinite Scroll List", "scroll the paginated list until Item 137 appears, then tap it", "Found item 137"), new("Modal Flow", "open the modal, continue, and confirm the dialog that follows", "Flow completed"), new("Bottom Tabs", "go to the Actions tab and complete the action there", "Action completed"), - new("Text Input Variations", "fill the username, the 4-digit PIN, and at least ten characters of notes, then submit", "Form submitted"), - new("Broken Accessibility", "complete the flow the screen describes until it says Access granted", "Access granted", Pixels: true, Gap: PixelsGap), - new("Vision Only", "complete the flow the screen describes until it says Sequence complete", "Sequence complete", Pixels: true, Gap: PixelsGap), - new("Gestures", "long-press the first target, swipe the card left, then double-tap the last target", "All gestures completed", Gap: "agent.act has no long press, and the Windows tool pack has no swipe, so the model cannot finish the first two steps"), - new("Async States", "wait for the screen to load, press Refresh to reveal the reward, then claim the reward", "Reward claimed"), - new("Debounced Search", "search for Benchmark Target and select exactly that result once it loads", "Selected Benchmark Target"), - new("Huge Virtualized List", "scroll to Row 0512 and tap it; the list has 600 rows and off-screen rows are not in the tree", "Found Row 0512"), + new( + "Text Input Variations", + "fill the username, the 4-digit PIN, and at least ten characters of notes, then submit", + "Form submitted" + ), + new( + "Broken Accessibility", + "complete the flow the screen describes until it says Access granted", + "Access granted", + Pixels: true, + Gap: PixelsGap + ), + new( + "Vision Only", + "complete the flow the screen describes until it says Sequence complete", + "Sequence complete", + Pixels: true, + Gap: PixelsGap + ), + new( + "Gestures", + "long-press the first target, swipe the card left, then double-tap the last target", + "All gestures completed", + Gap: "agent.act has no long press, and the Windows tool pack has no swipe, so the model cannot finish the first two steps" + ), + new( + "Async States", + "wait for the screen to load, press Refresh to reveal the reward, then claim the reward", + "Reward claimed" + ), + new( + "Debounced Search", + "search for Benchmark Target and select exactly that result once it loads", + "Selected Benchmark Target" + ), + new( + "Huge Virtualized List", + "scroll to Row 0512 and tap it; the list has 600 rows and off-screen rows are not in the tree", + "Found Row 0512" + ), // The values are spelled out so the recording replays. - new("Flattened Registration Form", "fill the registration form with first name Ada, last name Lovelace, email ada@example.com, and password Lovelace1815, then sign up until it says Account created", "Account created", Pixels: true, Gap: PixelsGap), + new( + "Flattened Registration Form", + "fill the registration form with first name Ada, last name Lovelace, email ada@example.com, and password Lovelace1815, then sign up until it says Account created", + "Account created", + Pixels: true, + Gap: PixelsGap + ), // The account is read off the screenshot, so the typed values are a gap in the recording by design. - new("Flattened Login", "log in with the email and password the screen shows as a hint", "Logged in successfully", Pixels: true, Gap: PixelsGap), - new("Sticky Chrome Target", "scroll down to the Accept terms button under the sticky footer, accept the terms, then tap Continue in the footer", "Terms accepted"), - new("Product Catalog", "open Trail Mix 500 g (not a look-alike), set the quantity to 2, add it to the cart, then open the cart", "Order ready: 2 × Trail Mix 500 g"), + new( + "Flattened Login", + "log in with the email and password the screen shows as a hint", + "Logged in successfully", + Pixels: true, + Gap: PixelsGap + ), + new( + "Sticky Chrome Target", + "scroll down to the Accept terms button under the sticky footer, accept the terms, then tap Continue in the footer", + "Terms accepted" + ), + new( + "Product Catalog", + "open Trail Mix 500 g (not a look-alike), set the quantity to 2, add it to the cart, then open the cart", + "Order ready: 2 × Trail Mix 500 g" + ), new("Error Recovery", "retry the failed load, then delete the draft and confirm", "Draft deleted"), - new("Choice Controls", "order a Medium pizza with exactly Cheese and Olives, enable rush delivery, and place the order", "Order placed: Medium with Cheese, Olives (rush)"), - new("Sequential Onboarding", "complete the signup wizard with email jane@example.com, first name Jane, last name Merchant, and phone 0612435678", "Onboarding complete"), + new( + "Choice Controls", + "order a Medium pizza with exactly Cheese and Olives, enable rush delivery, and place the order", + "Order placed: Medium with Cheese, Olives (rush)" + ), + new( + "Sequential Onboarding", + "complete the signup wizard with email jane@example.com, first name Jane, last name Merchant, and phone 0612435678", + "Onboarding complete" + ), ]; public static IEnumerable Cases() => - All.Select(scenario => new TestCaseData(scenario).SetName($"Act_completes_{scenario.Name.Replace(' ', '_')}").SetCategory(scenario.Name)); + All.Select(scenario => + new TestCaseData(scenario) + .SetName($"Act_completes_{scenario.Name.Replace(' ', '_')}") + .SetCategory(scenario.Name) + ); [TestCaseSource(nameof(Cases))] public async Task Act_completes(Scenario scenario) @@ -70,14 +143,19 @@ public async Task Act_completes(Scenario scenario) var account = scenario.WithAccount ? Credentials.User("benchmark") : null; var options = new ActOptions { - Params = account is null ? null : new Dictionary { ["username"] = account.Username, ["password"] = account.Password }, + Params = account is null + ? null + : new Dictionary { ["username"] = account.Username, ["password"] = account.Password }, }; await Agent.ActAsync(instruction, options); if (scenario.Pixels) { // The tree is hidden on purpose, so the message is judged from pixels. - await Agent.AssertAsync($"the screen shows the text \"{scenario.Success}\"", new AssertOptions { Vision = VisionMode.Only }); + await Agent.AssertAsync( + $"the screen shows the text \"{scenario.Success}\"", + new AssertOptions { Vision = VisionMode.Only } + ); return; } diff --git a/apps/WinAppBenchmark/App/BenchmarkApp.cs b/apps/WinAppBenchmark/App/BenchmarkApp.cs index c3a58bc80..2e0b1e050 100644 --- a/apps/WinAppBenchmark/App/BenchmarkApp.cs +++ b/apps/WinAppBenchmark/App/BenchmarkApp.cs @@ -22,14 +22,20 @@ public override Element Render() columns: [GridSize.Star()], rows: [GridSize.Auto, GridSize.Star()], When(headerShown, () => Header(nav, route)), - NavigationHost(nav, name => name == Examples.HomeTitle - ? Component() - : Examples.Find(name)?.Component() ?? TextBlock("Not found")).Grid(row: 1)); + NavigationHost(nav, name => + name == Examples.HomeTitle + ? Component() + : Examples.Find(name)?.Component() ?? TextBlock("Not found") + ) + .Grid(row: 1) + ); } private static Element Header(NavigationHandle nav, string title) => - HStack(8, - When(nav.CanGoBack, () => Button("Back", () => nav.GoBack()).AutomationId("back")), - Subtitle(title).AutomationId("screen-title").VAlign(VerticalAlignment.Center)) - .Padding(12, 8); + HStack( + 8, + When(nav.CanGoBack, () => Button("Back", () => nav.GoBack()).AutomationId("back")), + Subtitle(title).AutomationId("screen-title").VAlign(VerticalAlignment.Center) + ) + .Padding(12, 8); } diff --git a/apps/WinAppBenchmark/App/Examples.cs b/apps/WinAppBenchmark/App/Examples.cs index b7b9202e8..d984d4013 100644 --- a/apps/WinAppBenchmark/App/Examples.cs +++ b/apps/WinAppBenchmark/App/Examples.cs @@ -26,25 +26,90 @@ public static class Examples public static readonly IReadOnlyList All = [ - new("Login Form", "Fill credentials, handle validation errors, reach the logged-in state.", Component), - new("Infinite Scroll List", "Scroll a paginated list until a target item deep in the list is found.", Component), + new( + "Login Form", + "Fill credentials, handle validation errors, reach the logged-in state.", + Component + ), + new( + "Infinite Scroll List", + "Scroll a paginated list until a target item deep in the list is found.", + Component + ), new("Modal Flow", "Open a modal, confirm a dialog, and land on the success state.", Component), - new("Bottom Tabs", "Navigate between tabs and complete an action on the last tab.", Component, HeaderShown: false), - new("Text Input Variations", "Fill secure, multiline, and numeric inputs to unlock the submit button.", Component), - new("Broken Accessibility", "Whole screen hidden from the UI Automation tree: the snapshot is useless, vision required.", Component), - new("Vision Only", "UI Automation tree fully hidden like a canvas-rendered app: a pure pixel-driven flow.", Component), + new( + "Bottom Tabs", + "Navigate between tabs and complete an action on the last tab.", + Component, + HeaderShown: false + ), + new( + "Text Input Variations", + "Fill secure, multiline, and numeric inputs to unlock the submit button.", + Component + ), + new( + "Broken Accessibility", + "Whole screen hidden from the UI Automation tree: the snapshot is useless, vision required.", + Component + ), + new( + "Vision Only", + "UI Automation tree fully hidden like a canvas-rendered app: a pure pixel-driven flow.", + Component + ), new("Gestures", "Long-press, swipe left, and double-tap targets in sequence.", Component), new("Async States", "Wait out a loading screen, refresh, and catch a transient toast.", Component), - new("Debounced Search", "Type into a debounced search field, wait for async results, select the target.", Component), - new("Huge Virtualized List", "600 preloaded virtualized rows: the target sits far down and off-screen rows never enter the UI Automation tree, so the agent must size long scroll jumps from the scroll extent.", Component), - new("Flattened Registration Form", "Multi-field registration form hidden from the UI Automation tree: fields must be focused from vision and typed into via focused typing.", Component), - new("Flattened Login", "Login form hidden from the UI Automation tree: credentials must be filled from vision via focused fill, success visible only in pixels.", Component), - new("Sticky Chrome Target", "Accept button about three screens down in a non-virtualized scroll (present as an off-screen ref) under a sticky footer: tapping it must scroll it clear of the footer.", Component), - new("Product Catalog", "Disambiguate near-identical cards, drill into Trail Mix 500 g, set quantity 2, add to cart, review it.", Component), - new("Error Recovery", "Recover from a failed load via retry, then delete a draft through a destructive-confirm modal.", Component), - new("Choice Controls", "Select the exact size, toppings, and switch combination, then place the order.", Component), - new("Sequential Onboarding", "Multi-step signup wizard where each step auto-focuses a field and the Continue button sits at the bottom; the success screen echoes the entered values exactly.", Component), - new("Control Inventory", "The deterministic contract surface: plain controls with every state exposed, one exercise per runner verb. Not a hard surface.", Component), + new( + "Debounced Search", + "Type into a debounced search field, wait for async results, select the target.", + Component + ), + new( + "Huge Virtualized List", + "600 preloaded virtualized rows: the target sits far down and off-screen rows never enter the UI Automation tree, so the agent must size long scroll jumps from the scroll extent.", + Component + ), + new( + "Flattened Registration Form", + "Multi-field registration form hidden from the UI Automation tree: fields must be focused from vision and typed into via focused typing.", + Component + ), + new( + "Flattened Login", + "Login form hidden from the UI Automation tree: credentials must be filled from vision via focused fill, success visible only in pixels.", + Component + ), + new( + "Sticky Chrome Target", + "Accept button about three screens down in a non-virtualized scroll (present as an off-screen ref) under a sticky footer: tapping it must scroll it clear of the footer.", + Component + ), + new( + "Product Catalog", + "Disambiguate near-identical cards, drill into Trail Mix 500 g, set quantity 2, add to cart, review it.", + Component + ), + new( + "Error Recovery", + "Recover from a failed load via retry, then delete a draft through a destructive-confirm modal.", + Component + ), + new( + "Choice Controls", + "Select the exact size, toppings, and switch combination, then place the order.", + Component + ), + new( + "Sequential Onboarding", + "Multi-step signup wizard where each step auto-focuses a field and the Continue button sits at the bottom; the success screen echoes the entered values exactly.", + Component + ), + new( + "Control Inventory", + "The deterministic contract surface: plain controls with every state exposed, one exercise per runner verb. Not a hard surface.", + Component + ), ]; /// The example named , or null for the home route. diff --git a/apps/WinAppBenchmark/App/HomeList.cs b/apps/WinAppBenchmark/App/HomeList.cs index 34aca2a82..87201752a 100644 --- a/apps/WinAppBenchmark/App/HomeList.cs +++ b/apps/WinAppBenchmark/App/HomeList.cs @@ -21,14 +21,19 @@ public override Element Render() var examples = Examples.All; var rows = (examples.Count + 1) / 2; - return ScrollView(Grid( - columns: [GridSize.Star(), GridSize.Star()], - rows: [.. Enumerable.Repeat(GridSize.Px(RowHeight), rows)], - [.. examples.Select((example, index) => Row(nav, example).Grid(row: index / 2, column: index % 2))])); + return ScrollView( + Grid( + columns: [GridSize.Star(), GridSize.Star()], + rows: [.. Enumerable.Repeat(GridSize.Px(RowHeight), rows)], + [.. examples.Select((example, index) => Row(nav, example).Grid(row: index / 2, column: index % 2))] + ) + ); } private static Element Row(NavigationHandle nav, Example example) => - Button(TextBlock(example.Name).SemiBold().FontSize(13).TextWrapping().MaxLines(2), () => nav.Navigate(example.Name)) + Button(TextBlock(example.Name).SemiBold().FontSize(13).TextWrapping().MaxLines(2), () => + nav.Navigate(example.Name) + ) .AutomationId(example.Name) .AutomationName($"{example.Name}. {example.Description}") .Height(RowHeight) diff --git a/apps/WinAppBenchmark/App/Support.cs b/apps/WinAppBenchmark/App/Support.cs index 0939fe1a8..1ed86a292 100644 --- a/apps/WinAppBenchmark/App/Support.cs +++ b/apps/WinAppBenchmark/App/Support.cs @@ -10,7 +10,8 @@ namespace WinAppBenchmark.App; public static class Support { /// The terminal element of a scenario whose tree is intact, AutomationId "success-message". - public static Element Success(string text) => TextBlock(text).SemiBold().FontSize(20).TextWrapping().AutomationId("success-message"); + public static Element Success(string text) => + TextBlock(text).SemiBold().FontSize(20).TextWrapping().AutomationId("success-message"); /// The on-screen instruction of a scenario. public static Element Hint(string text) => Body(text).TextWrapping().Foreground("#555555"); @@ -22,23 +23,25 @@ public static class Support public static void After(int milliseconds, CancellationToken token, Action action) { var queue = DispatcherQueue.GetForCurrentThread(); - _ = Task.Delay(milliseconds, token).ContinueWith( - delay => - { - if (delay.Status == TaskStatus.RanToCompletion) + _ = Task.Delay(milliseconds, token) + .ContinueWith( + delay => { - queue.TryEnqueue(() => + if (delay.Status == TaskStatus.RanToCompletion) { - if (!token.IsCancellationRequested) + queue.TryEnqueue(() => { - action(); - } - }); - } - }, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + if (!token.IsCancellationRequested) + { + action(); + } + }); + } + }, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default + ); } /// A solid brush from a six or eight digit hex color. @@ -47,6 +50,8 @@ public static SolidColorBrush Brush(string hex) var digits = hex.TrimStart('#'); var value = Convert.ToUInt32(digits, 16); var alpha = digits.Length == 8 ? (byte)(value >> 24) : (byte)0xFF; - return new SolidColorBrush(Windows.UI.Color.FromArgb(alpha, (byte)(value >> 16), (byte)(value >> 8), (byte)value)); + return new SolidColorBrush( + Windows.UI.Color.FromArgb(alpha, (byte)(value >> 16), (byte)(value >> 8), (byte)value) + ); } } diff --git a/apps/WinAppBenchmark/Examples/AsyncStates.cs b/apps/WinAppBenchmark/Examples/AsyncStates.cs index 1f8f8ddff..545164a50 100644 --- a/apps/WinAppBenchmark/Examples/AsyncStates.cs +++ b/apps/WinAppBenchmark/Examples/AsyncStates.cs @@ -25,13 +25,16 @@ public override Element Render() var (claimed, setClaimed) = UseState(false); var lifetime = UseRef(null); - UseEffect(() => - { - var cts = new CancellationTokenSource(); - lifetime.Current = cts; - After(InitialLoadMilliseconds, cts.Token, () => setLoading(false)); - return () => cts.Cancel(); - }, Array.Empty()); + UseEffect( + () => + { + var cts = new CancellationTokenSource(); + lifetime.Current = cts; + After(InitialLoadMilliseconds, cts.Token, () => setLoading(false)); + return () => cts.Cancel(); + }, + Array.Empty() + ); var token = lifetime.Current?.Token ?? CancellationToken.None; @@ -60,32 +63,37 @@ void Claim() if (loading) { - return VStack(12, - ProgressRing().AutomationId("initial-loading"), - Hint("Loading…")) - .Padding(24); + return VStack(12, ProgressRing().AutomationId("initial-loading"), Hint("Loading…")).Padding(24); } - Element content = claimed - ? Success("Reward claimed") - : rewardVisible - ? Button("Claim reward", Claim).AutomationId("claim-button") - : Hint("Refresh to reveal your reward"); + Element content = + claimed ? Success("Reward claimed") + : rewardVisible ? Button("Claim reward", Claim).AutomationId("claim-button") + : Hint("Refresh to reveal your reward"); return Grid( columns: [GridSize.Star()], rows: [GridSize.Auto, GridSize.Star()], - HStack(12, - Button("Refresh", Refresh).IsEnabled(!refreshing).AutomationId("refresh-button"), - When(refreshing, () => ProgressRing().AutomationId("refreshing"))) + HStack( + 12, + Button("Refresh", Refresh).IsEnabled(!refreshing).AutomationId("refresh-button"), + When(refreshing, () => ProgressRing().AutomationId("refreshing")) + ) .Padding(24, 16), - ScrollView(VStack(12, content).Padding(24)).AutomationName("Reward area").AutomationId("reward-scroll").Grid(row: 1), - When(toastVisible, () => Border(Body("Claiming reward…").Foreground("#ffffff").Padding(16, 12)) - .Background("#cc222222") - .CornerRadius(8) - .HAlign(HorizontalAlignment.Center) - .VAlign(VerticalAlignment.Bottom) - .Margin(0, 0, 0, 24) - .AutomationId("toast")).Grid(row: 1)); + ScrollView(VStack(12, content).Padding(24)) + .AutomationName("Reward area") + .AutomationId("reward-scroll") + .Grid(row: 1), + When(toastVisible, () => + Border(Body("Claiming reward…").Foreground("#ffffff").Padding(16, 12)) + .Background("#cc222222") + .CornerRadius(8) + .HAlign(HorizontalAlignment.Center) + .VAlign(VerticalAlignment.Bottom) + .Margin(0, 0, 0, 24) + .AutomationId("toast") + ) + .Grid(row: 1) + ); } } diff --git a/apps/WinAppBenchmark/Examples/BottomTabs.cs b/apps/WinAppBenchmark/Examples/BottomTabs.cs index 739210a0f..d0fd65c8e 100644 --- a/apps/WinAppBenchmark/Examples/BottomTabs.cs +++ b/apps/WinAppBenchmark/Examples/BottomTabs.cs @@ -19,12 +19,17 @@ public override Element Render() Element content = tab switch { "Feed" => VStack(12, Title("Feed").AutomationId("feed-tab-content")), - "Actions" => VStack(12, done - ? Success("Action completed") - : Button("Complete action", () => setDone(true)).AutomationId("complete-action-button")), - _ => VStack(12, + "Actions" => VStack( + 12, + done + ? Success("Action completed") + : Button("Complete action", () => setDone(true)).AutomationId("complete-action-button") + ), + _ => VStack( + 12, Title("Home").AutomationId("home-tab-content"), - Hint("Go to the Actions tab and press the button there.")), + Hint("Go to the Actions tab and press the button there.") + ), }; return Grid( @@ -32,9 +37,8 @@ public override Element Render() rows: [GridSize.Auto, GridSize.Star(), GridSize.Auto], Button("Back", () => nav.GoBack()).AutomationId("back").Margin(12, 8), content.Padding(24).Grid(row: 1), - HStack(8, [.. Tabs.Select(name => TabButton(name, tab, setTab))]) - .Padding(12, 8) - .Grid(row: 2)); + HStack(8, [.. Tabs.Select(name => TabButton(name, tab, setTab))]).Padding(12, 8).Grid(row: 2) + ); } private static Element TabButton(string name, string current, Action select) => diff --git a/apps/WinAppBenchmark/Examples/BrokenAccessibility.cs b/apps/WinAppBenchmark/Examples/BrokenAccessibility.cs index cf8bebdd5..e25fc1eb2 100644 --- a/apps/WinAppBenchmark/Examples/BrokenAccessibility.cs +++ b/apps/WinAppBenchmark/Examples/BrokenAccessibility.cs @@ -15,7 +15,12 @@ public sealed class BrokenAccessibility : Component { private const string SecretCode = "7291"; - private enum Step { Pick, Code, Done } + private enum Step + { + Pick, + Code, + Done, + } public override Element Render() { @@ -25,37 +30,61 @@ public override Element Render() return step switch { - Step.Pick => VStack(24, - Body("Tap the green circle to continue").AccessibilityView(AccessibilityView.Raw), - When(wrongPick, () => Body("Wrong shape, try again").Foreground("#b00020").AccessibilityView(AccessibilityView.Raw)), - HStack(24, - Ellipse().Fill(Brush("#c62828")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)), - Rectangle().Fill(Brush("#2e7d32")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)), - Ellipse().Fill(Brush("#2e7d32")).Size(64, 64).OnTapped((_, _) => - { - setWrongPick(false); - setStep(Step.Code); - }), - Ellipse().Fill(Brush("#1565c0")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)))) + Step.Pick => VStack( + 24, + Body("Tap the green circle to continue").AccessibilityView(AccessibilityView.Raw), + When(wrongPick, () => + Body("Wrong shape, try again").Foreground("#b00020").AccessibilityView(AccessibilityView.Raw) + ), + HStack( + 24, + Ellipse().Fill(Brush("#c62828")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)), + Rectangle().Fill(Brush("#2e7d32")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)), + Ellipse() + .Fill(Brush("#2e7d32")) + .Size(64, 64) + .OnTapped( + (_, _) => + { + setWrongPick(false); + setStep(Step.Code); + } + ), + Ellipse().Fill(Brush("#1565c0")).Size(64, 64).OnTapped((_, _) => setWrongPick(true)) + ) + ) + .Padding(24), + Step.Code => VStack( + 24, + Body($"Enter the code {SecretCode} and press the arrow").AccessibilityView(AccessibilityView.Raw), + HStack( + 16, + TextBox(code, setCode).MaxLength(4).Width(120).AccessibilityView(AccessibilityView.Raw), + Grid( + columns: [GridSize.Px(56)], + rows: [GridSize.Px(56)], + Ellipse().Fill(Brush(code == SecretCode ? "#2e7d32" : "#9e9e9e")).Size(56, 56), + TextBlock("→") + .FontSize(24) + .Foreground("#ffffff") + .HAlign(HorizontalAlignment.Center) + .VAlign(VerticalAlignment.Center) + .AccessibilityView(AccessibilityView.Raw) + ) + .OnTapped( + (_, _) => + { + if (code == SecretCode) + { + setStep(Step.Done); + } + } + ) + ) + ) .Padding(24), - Step.Code => VStack(24, - Body($"Enter the code {SecretCode} and press the arrow").AccessibilityView(AccessibilityView.Raw), - HStack(16, - TextBox(code, setCode).MaxLength(4).Width(120).AccessibilityView(AccessibilityView.Raw), - Grid( - columns: [GridSize.Px(56)], - rows: [GridSize.Px(56)], - Ellipse().Fill(Brush(code == SecretCode ? "#2e7d32" : "#9e9e9e")).Size(56, 56), - TextBlock("→").FontSize(24).Foreground("#ffffff").HAlign(HorizontalAlignment.Center).VAlign(VerticalAlignment.Center).AccessibilityView(AccessibilityView.Raw)) - .OnTapped((_, _) => - { - if (code == SecretCode) - { - setStep(Step.Done); - } - }))) + _ => VStack(TextBlock("Access granted").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)) .Padding(24), - _ => VStack(TextBlock("Access granted").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)).Padding(24), }; } } diff --git a/apps/WinAppBenchmark/Examples/ChoiceControls.cs b/apps/WinAppBenchmark/Examples/ChoiceControls.cs index 676e68d9d..c7c4464e3 100644 --- a/apps/WinAppBenchmark/Examples/ChoiceControls.cs +++ b/apps/WinAppBenchmark/Examples/ChoiceControls.cs @@ -25,42 +25,73 @@ public override Element Render() var (notes, setNotes) = UseState(""); var (submitted, setSubmitted) = UseState(false); - var orderValid = size == "Medium" + var orderValid = + size == "Medium" && toppings.Count == RequiredToppings.Length && RequiredToppings.All(toppings.Contains) && rushDelivery; // Toggles a topping checkbox on or off. void ToggleTopping(string topping) => - setToppings(toppings.Contains(topping) ? toppings.Where(other => other != topping).ToHashSet() : [.. toppings, topping]); + setToppings( + toppings.Contains(topping) + ? toppings.Where(other => other != topping).ToHashSet() + : [.. toppings, topping] + ); if (submitted) { return VStack(Success("Order placed: Medium with Cheese, Olives (rush)")).Padding(24); } - return ScrollView(VStack(12, [ - Hint("Order a Medium pizza with exactly Cheese and Olives, enable rush delivery, then place the order."), - BodyStrong("Size"), - HStack(12, [.. Sizes.Select(option => - RadioButton(option, size == option, isChecked => - { - if (isChecked) - { - setSize(option); - } - }, groupName: "size") - .AutomationId($"size-{option.ToLowerInvariant()}") - .WithKey(option))]), - BodyStrong("Toppings"), - .. Toppings.Select(topping => - CheckBox(toppings.Contains(topping), _ => ToggleTopping(topping), label: topping) - .AutomationId($"topping-{topping.ToLowerInvariant()}") - .WithKey(topping)), - ToggleSwitch(rushDelivery, setRushDelivery, header: "Rush delivery").AutomationName("Rush delivery").AutomationId("rush-delivery"), - BodyStrong("Delivery notes"), - TextBox(notes, setNotes, placeholderText: "Ring the doorbell twice").AutomationName("Delivery notes").AutomationId("delivery-notes"), - Button("Place order", () => setSubmitted(true)).IsEnabled(orderValid).AutomationId("place-order"), - ]).Padding(24)); + return ScrollView( + VStack( + 12, + [ + Hint( + "Order a Medium pizza with exactly Cheese and Olives, enable rush delivery, then place the order." + ), + BodyStrong("Size"), + HStack( + 12, + [ + .. Sizes.Select(option => + RadioButton( + option, + size == option, + isChecked => + { + if (isChecked) + { + setSize(option); + } + }, + groupName: "size" + ) + .AutomationId($"size-{option.ToLowerInvariant()}") + .WithKey(option) + ), + ] + ), + BodyStrong("Toppings"), + .. Toppings.Select(topping => + CheckBox(toppings.Contains(topping), _ => ToggleTopping(topping), label: topping) + .AutomationId($"topping-{topping.ToLowerInvariant()}") + .WithKey(topping) + ), + ToggleSwitch(rushDelivery, setRushDelivery, header: "Rush delivery") + .AutomationName("Rush delivery") + .AutomationId("rush-delivery"), + BodyStrong("Delivery notes"), + TextBox(notes, setNotes, placeholderText: "Ring the doorbell twice") + .AutomationName("Delivery notes") + .AutomationId("delivery-notes"), + Button("Place order", () => setSubmitted(true)) + .IsEnabled(orderValid) + .AutomationId("place-order"), + ] + ) + .Padding(24) + ); } } diff --git a/apps/WinAppBenchmark/Examples/ControlInventory.cs b/apps/WinAppBenchmark/Examples/ControlInventory.cs index 14537c425..3626d998e 100644 --- a/apps/WinAppBenchmark/Examples/ControlInventory.cs +++ b/apps/WinAppBenchmark/Examples/ControlInventory.cs @@ -26,24 +26,38 @@ public override Element Render() { "Toggles" => Component(), "Gestures" => Component(), - "Device" => VStack(8, - Body($"{Math.Round(width)}x{Math.Round(height)}").AutomationId("window-size")), + "Device" => VStack(8, Body($"{Math.Round(width)}x{Math.Round(height)}").AutomationId("window-size")), _ => Component(), }; - return ScrollView(VStack(8, - Body("Plain controls, every state exposed").AutomationName("Inventory heading").AutomationId("inventory-header"), - Body($"scheme: {scheme.ToString().ToLowerInvariant()}").AutomationId("color-scheme"), - Body($"orientation: {(width > height ? "landscape" : "portrait")}").AutomationId("orientation"), - HStack(8, [.. Sections.Select(name => - Button(name, () => setSection(name)) - .AutomationName(name) - .AutomationId($"tab-{name.ToLowerInvariant()}") - .IsEnabled(name != section) - .WithKey(name))]).AutomationName("Sections").AutomationId("section-tabs"), - body) - .Padding(24)) - .AutomationName("Inventory").AutomationId("inventory-scroll"); + return ScrollView( + VStack( + 8, + Body("Plain controls, every state exposed") + .AutomationName("Inventory heading") + .AutomationId("inventory-header"), + Body($"scheme: {scheme.ToString().ToLowerInvariant()}").AutomationId("color-scheme"), + Body($"orientation: {(width > height ? "landscape" : "portrait")}").AutomationId("orientation"), + HStack( + 8, + [ + .. Sections.Select(name => + Button(name, () => setSection(name)) + .AutomationName(name) + .AutomationId($"tab-{name.ToLowerInvariant()}") + .IsEnabled(name != section) + .WithKey(name) + ), + ] + ) + .AutomationName("Sections") + .AutomationId("section-tabs"), + body + ) + .Padding(24) + ) + .AutomationName("Inventory") + .AutomationId("inventory-scroll"); } } @@ -52,7 +66,9 @@ public sealed class FieldsSection : Component { // The name a key prints as: a letter in lower case, any other key as the platform names it ("Enter"). private static string KeyName(Windows.System.VirtualKey key) => - key is >= Windows.System.VirtualKey.A and <= Windows.System.VirtualKey.Z ? key.ToString().ToLowerInvariant() : key.ToString(); + key is >= Windows.System.VirtualKey.A and <= Windows.System.VirtualKey.Z + ? key.ToString().ToLowerInvariant() + : key.ToString(); public override Element Render() { @@ -64,40 +80,56 @@ public override Element Render() var (focused, setFocused) = UseState("none"); var (focusRef, requestFocus) = this.UseElementFocus(); - UseEffect(() => - { - if (focusShown) + UseEffect( + () => { - requestFocus(); - } - }, focusShown); + if (focusShown) + { + requestFocus(); + } + }, + focusShown + ); // Clears the focus status only when the field losing focus still owns it. void Blurred(string field) => setFocused(focused == field ? "none" : focused); if (focusShown) { - return VStack(8, - TextBox("", _ => { }).Ref(focusRef).AutomationName("Autofocus field").AutomationId("autofocus-input") + return VStack( + 8, + TextBox("", _ => { }) + .Ref(focusRef) + .AutomationName("Autofocus field") + .AutomationId("autofocus-input") .OnGotFocus((_, _) => setFocused("Autofocus field")) .OnLostFocus((_, _) => Blurred("Autofocus field")), - TextBox("", _ => { }).AutomationName("Second field").AutomationId("second-input") + TextBox("", _ => { }) + .AutomationName("Second field") + .AutomationId("second-input") .OnGotFocus((_, _) => setFocused("Second field")) .OnLostFocus((_, _) => Blurred("Second field")), - Body($"focus: {focused}").AutomationId("focus-status")); + Body($"focus: {focused}").AutomationId("focus-status") + ); } - return VStack(8, - TextBox(name, setName, placeholderText: "Type your name").AutomationName("Name field").AutomationId("name-input"), + return VStack( + 8, + TextBox(name, setName, placeholderText: "Type your name") + .AutomationName("Name field") + .AutomationId("name-input"), Body($"name: {name}").AutomationId("name-echo"), - PasswordBox(passphrase, setPassphrase, placeholderText: "Passphrase").AutomationName("Passphrase field").AutomationId("passphrase-input"), + PasswordBox(passphrase, setPassphrase, placeholderText: "Passphrase") + .AutomationName("Passphrase field") + .AutomationId("passphrase-input"), Body($"passphrase length: {passphrase.Length}").AutomationId("passphrase-length"), TextBox(keyText, setKeyText, placeholderText: "Key echo") .AutomationName("Key echo field") .AutomationId("key-input") .OnKeyDown((_, e) => setLastKey(KeyName(e.Key))), Body($"key: {lastKey}").AutomationId("key-status"), - Button("Show focus fields", () => setFocusShown(true)).AutomationId("show-focus-fields")); + Button("Show focus fields", () => setFocusShown(true)).AutomationId("show-focus-fields") + ); } } @@ -113,35 +145,59 @@ public override Element Render() var (size, setSize) = UseState("Small"); var (delayed, setDelayed) = UseState("arming"); - UseEffect(() => - { - var cts = new CancellationTokenSource(); - After(1500, cts.Token, () => setDelayed("ready")); - return () => cts.Cancel(); - }, Array.Empty()); + UseEffect( + () => + { + var cts = new CancellationTokenSource(); + After(1500, cts.Token, () => setDelayed("ready")); + return () => cts.Cancel(); + }, + Array.Empty() + ); - return VStack(8, + return VStack( + 8, ToggleSwitch(wifi, setWifi, header: "Wi-Fi").AutomationName("Wi-Fi switch").AutomationId("wifi-switch"), Body($"wifi: {(wifi ? "on" : "off")}").AutomationId("wifi-status"), - CheckBox(newsletter, setNewsletter, label: "Newsletter").AutomationName("Newsletter").AutomationId("newsletter-checkbox"), + CheckBox(newsletter, setNewsletter, label: "Newsletter") + .AutomationName("Newsletter") + .AutomationId("newsletter-checkbox"), Body($"newsletter: {(newsletter ? "on" : "off")}").AutomationId("newsletter-status"), - HStack(8, [.. Sizes.Select(option => - RadioButton(option, size == option, isChecked => - { - if (isChecked) - { - setSize(option); - } - }, groupName: "inventory-size") - .AutomationId($"size-{option.ToLowerInvariant()}") - .WithKey(option))]).AutomationName("Size").AutomationId("size-group"), + HStack( + 8, + [ + .. Sizes.Select(option => + RadioButton( + option, + size == option, + isChecked => + { + if (isChecked) + { + setSize(option); + } + }, + groupName: "inventory-size" + ) + .AutomationId($"size-{option.ToLowerInvariant()}") + .WithKey(option) + ), + ] + ) + .AutomationName("Size") + .AutomationId("size-group"), Body($"size: {size}").AutomationId("size-status"), - HStack(8, + HStack( + 8, Button("Locked", () => { }).IsEnabled(false).AutomationId("locked-button"), - Button("Delayed", () => setDelayed("pressed")).IsEnabled(delayed != "arming").AutomationId("delayed-button")), + Button("Delayed", () => setDelayed("pressed")) + .IsEnabled(delayed != "arming") + .AutomationId("delayed-button") + ), Body($"delayed: {delayed}").AutomationId("delayed-status"), Body("Now you see me").IsVisible(false).AutomationId("ghost-text"), - Body("Now you see me").AutomationId("twin-text")); + Body("Now you see me").AutomationId("twin-text") + ); } } @@ -150,7 +206,12 @@ public sealed class GesturesSection : Component { private const int DoubleTapWindowMilliseconds = 300; - private static readonly (string Name, string Price)[] Fruits = [("Apple", "$1"), ("Banana", "$2"), ("Cherry", "$3")]; + private static readonly (string Name, string Price)[] Fruits = + [ + ("Apple", "$1"), + ("Banana", "$2"), + ("Cherry", "$3"), + ]; public override Element Render() { @@ -176,35 +237,62 @@ void DoubleTapCandidate() static string Point(double x, double y) => $"{Math.Round(x)},{Math.Round(y)}"; - return VStack(8, - HStack(8, + return VStack( + 8, + HStack( + 8, Button("Hold me", null) - .OnLongPress(() => setGesture("long press"), TimeSpan.FromMilliseconds(500), enableMouseEmulation: true) + .OnLongPress( + () => setGesture("long press"), + TimeSpan.FromMilliseconds(500), + enableMouseEmulation: true + ) .AutomationId("long-press-target"), - Button("Double-tap me", DoubleTapCandidate).AutomationId("double-tap-target")), + Button("Double-tap me", DoubleTapCandidate).AutomationId("double-tap-target") + ), Body($"gesture: {gesture}").AutomationId("gesture-status"), Body(taps).AutomationId("tap-count"), - Rectangle().Fill(Brush("#e0e0e0")).Size(240, 100) + Rectangle() + .Fill(Brush("#e0e0e0")) + .Size(240, 100) .AutomationName("Tap pad") .AutomationId("tap-pad") - .OnPointerPressed((sender, e) => - { - var at = e.GetCurrentPoint((UIElement)sender).Position; - setPad(Point(at.X, at.Y)); - }), + .OnPointerPressed( + (sender, e) => + { + var at = e.GetCurrentPoint((UIElement)sender).Position; + setPad(Point(at.X, at.Y)); + } + ), Body($"pad: {pad}").AutomationId("pad-status"), - Rectangle().Fill(Brush("#bbdefb")).Size(240, 100) + Rectangle() + .Fill(Brush("#bbdefb")) + .Size(240, 100) .AutomationName("Swipe pad") .AutomationId("swipe-pad") .OnPointerPressed((sender, e) => swipeStart.Current = e.GetCurrentPoint((UIElement)sender).Position) - .OnPointerReleased((sender, e) => - { - var from = swipeStart.Current; - var to = e.GetCurrentPoint((UIElement)sender).Position; - setSwipe($"{Point(from.X, from.Y)} to {Point(to.X, to.Y)}"); - }), + .OnPointerReleased( + (sender, e) => + { + var from = swipeStart.Current; + var to = e.GetCurrentPoint((UIElement)sender).Position; + setSwipe($"{Point(from.X, from.Y)} to {Point(to.X, to.Y)}"); + } + ), Body($"swipe: {swipe}").AutomationId("swipe-status"), - VStack(4, [.. Fruits.Select(fruit => - HStack(8, Body(fruit.Name), Body(fruit.Price)).AutomationName($"{fruit.Name} row").AutomationId("fruit-row").WithKey(fruit.Name))]).AutomationName("Fruit list").AutomationId("fruit-list")); + VStack( + 4, + [ + .. Fruits.Select(fruit => + HStack(8, Body(fruit.Name), Body(fruit.Price)) + .AutomationName($"{fruit.Name} row") + .AutomationId("fruit-row") + .WithKey(fruit.Name) + ), + ] + ) + .AutomationName("Fruit list") + .AutomationId("fruit-list") + ); } } diff --git a/apps/WinAppBenchmark/Examples/DebouncedSearch.cs b/apps/WinAppBenchmark/Examples/DebouncedSearch.cs index 97eeec73b..d561a7a01 100644 --- a/apps/WinAppBenchmark/Examples/DebouncedSearch.cs +++ b/apps/WinAppBenchmark/Examples/DebouncedSearch.cs @@ -40,27 +40,30 @@ public override Element Render() var (searching, setSearching) = UseState(false); var (selected, setSelected) = UseState(null); - UseEffect(() => - { - var cts = new CancellationTokenSource(); - After(DebounceMilliseconds, cts.Token, () => + UseEffect( + () => { - if (query.Trim().Length == 0) + var cts = new CancellationTokenSource(); + After(DebounceMilliseconds, cts.Token, () => { - setResults([]); - setSearching(false); - return; - } + if (query.Trim().Length == 0) + { + setResults([]); + setSearching(false); + return; + } - setSearching(true); - After(FetchMilliseconds, cts.Token, () => - { - setResults(SearchDataset(query)); - setSearching(false); + setSearching(true); + After(FetchMilliseconds, cts.Token, () => + { + setResults(SearchDataset(query)); + setSearching(false); + }); }); - }); - return () => cts.Cancel(); - }, query); + return () => cts.Cancel(); + }, + query + ); if (selected == Target) { @@ -69,21 +72,35 @@ public override Element Render() Element list = searching ? ProgressRing().AutomationId("search-loading").Padding(12) - : ScrollView(VStack(4, [ - .. results.Select(item => Button(TextBlock(item), () => setSelected(item)) - .AutomationId($"result-{item}") - .HAlign(HorizontalAlignment.Stretch) - .WithKey(item)), - When(results.Count == 0 && query.Trim().Length > 0, () => Hint("No results")), - ])).AutomationName("Results").AutomationId("search-results"); + : ScrollView( + VStack( + 4, + [ + .. results.Select(item => + Button(TextBlock(item), () => setSelected(item)) + .AutomationId($"result-{item}") + .HAlign(HorizontalAlignment.Stretch) + .WithKey(item) + ), + When(results.Count == 0 && query.Trim().Length > 0, () => Hint("No results")), + ] + ) + ) + .AutomationName("Results") + .AutomationId("search-results"); return Grid( columns: [GridSize.Star()], rows: [GridSize.Auto, GridSize.Star()], - VStack(12, - Hint($"Search for and select \"{Target}\""), - TextBox(query, setQuery, placeholderText: "Search…").AutomationName("Search").AutomationId("search-input")) + VStack( + 12, + Hint($"Search for and select \"{Target}\""), + TextBox(query, setQuery, placeholderText: "Search…") + .AutomationName("Search") + .AutomationId("search-input") + ) .Padding(24, 16), - list.Padding(24, 0).Grid(row: 1)); + list.Padding(24, 0).Grid(row: 1) + ); } } diff --git a/apps/WinAppBenchmark/Examples/ErrorRecovery.cs b/apps/WinAppBenchmark/Examples/ErrorRecovery.cs index 3390f874c..4369670ee 100644 --- a/apps/WinAppBenchmark/Examples/ErrorRecovery.cs +++ b/apps/WinAppBenchmark/Examples/ErrorRecovery.cs @@ -14,7 +14,12 @@ public sealed class ErrorRecovery : Component { private const int LoadMilliseconds = 1500; - private enum Phase { Loading, Error, Loaded } + private enum Phase + { + Loading, + Error, + Loaded, + } public override Element Render() { @@ -24,17 +29,20 @@ public override Element Render() var attempts = UseRef(0); var pending = UseRef(null); - UseEffect(() => - { - var cts = new CancellationTokenSource(); - pending.Current = cts; - After(LoadMilliseconds, cts.Token, () => + UseEffect( + () => { - attempts.Current += 1; - setPhase(Phase.Error); - }); - return () => cts.Cancel(); - }, Array.Empty()); + var cts = new CancellationTokenSource(); + pending.Current = cts; + After(LoadMilliseconds, cts.Token, () => + { + attempts.Current += 1; + setPhase(Phase.Error); + }); + return () => cts.Cancel(); + }, + Array.Empty() + ); // Retries the failed load; the second attempt deterministically succeeds. void Retry() @@ -49,38 +57,46 @@ void Retry() if (phase == Phase.Loading) { - return VStack(12, - ProgressRing().AutomationId("loading-indicator"), - Hint("Loading drafts…")) - .Padding(24); + return VStack(12, ProgressRing().AutomationId("loading-indicator"), Hint("Loading drafts…")).Padding(24); } if (phase == Phase.Error) { - return VStack(12, - InfoBar("Network error", "could not load drafts").Error().AutomationId("error-banner"), - Button("Retry", Retry).AutomationId("retry-button")) + return VStack( + 12, + InfoBar("Network error", "could not load drafts").Error().AutomationId("error-banner"), + Button("Retry", Retry).AutomationId("retry-button") + ) .Padding(24); } var drafts = deleted ? VStack(Success("Draft deleted")) - : VStack(12, + : VStack( + 12, Subtitle("Drafts"), Body("Untitled draft — “Quarterly numbers…”"), - Button("Delete draft", () => setConfirmVisible(true)).AutomationId("delete-draft")); + Button("Delete draft", () => setConfirmVisible(true)).AutomationId("delete-draft") + ); - var confirm = ScrollViewer(VStack(12, - Subtitle("Delete this draft?"), - Hint("This action cannot be undone."), - HStack(8, - Button("Cancel", () => setConfirmVisible(false)).AutomationId("confirm-cancel"), - Button("Delete", () => - { - setConfirmVisible(false); - setDeleted(true); - }).AutomationId("confirm-delete"))) - .Padding(20)) + var confirm = ScrollViewer( + VStack( + 12, + Subtitle("Delete this draft?"), + Hint("This action cannot be undone."), + HStack( + 8, + Button("Cancel", () => setConfirmVisible(false)).AutomationId("confirm-cancel"), + Button("Delete", () => + { + setConfirmVisible(false); + setDeleted(true); + }) + .AutomationId("confirm-delete") + ) + ) + .Padding(20) + ) .Background(Theme.CardBackground) .CornerRadius(12) .VAlign(VerticalAlignment.Center) @@ -90,6 +106,7 @@ void Retry() columns: [GridSize.Star()], rows: [GridSize.Star()], drafts.Padding(24), - When(confirmVisible, () => Border(confirm).Background("#80000000"))); + When(confirmVisible, () => Border(confirm).Background("#80000000")) + ); } } diff --git a/apps/WinAppBenchmark/Examples/FlattenedForm.cs b/apps/WinAppBenchmark/Examples/FlattenedForm.cs index e96520d87..e89a0f551 100644 --- a/apps/WinAppBenchmark/Examples/FlattenedForm.cs +++ b/apps/WinAppBenchmark/Examples/FlattenedForm.cs @@ -14,7 +14,13 @@ namespace WinAppBenchmark.Examples; /// public sealed class FlattenedForm : Component { - private enum Field { FirstName, LastName, Email, Password } + private enum Field + { + FirstName, + LastName, + Email, + Password, + } private static readonly (Field Key, string Label, bool Secure)[] Fields = [ @@ -24,13 +30,14 @@ private static readonly (Field Key, string Label, bool Secure)[] Fields = (Field.Password, "Set password", true), ]; - private static string ErrorOf(Field key) => key switch - { - Field.FirstName => "Please enter your first name", - Field.LastName => "Please enter your last name", - Field.Email => "Please enter a valid email address", - _ => "Password must be at least 8 characters", - }; + private static string ErrorOf(Field key) => + key switch + { + Field.FirstName => "Please enter your first name", + Field.LastName => "Please enter your last name", + Field.Email => "Please enter a valid email address", + _ => "Password must be at least 8 characters", + }; // Validates one field the same way on every run so failures are deterministic: names must be // non-empty, the email needs an "@", and the password needs at least 8 characters. @@ -61,32 +68,53 @@ void SetValue(Field key, string value) if (done) { - return VStack(TextBlock("Account created").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)).Padding(24); + return VStack(TextBlock("Account created").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)) + .Padding(24); } - var filler = "Passwords must contain a minimum of 8 characters. By signing up you confirm you have read the benchmark terms. This filler paragraph exists so the form spans roughly two screens and the scroll indicator reports multiple pages, matching the production app this scenario was distilled from."; - var trailer = "More filler content below the primary action: support links, privacy policy, and terms and conditions would normally live here. It pads the scroll extent so off-screen estimation has something to measure."; + var filler = + "Passwords must contain a minimum of 8 characters. By signing up you confirm you have read the benchmark terms. This filler paragraph exists so the form spans roughly two screens and the scroll indicator reports multiple pages, matching the production app this scenario was distilled from."; + var trailer = + "More filler content below the primary action: support links, privacy policy, and terms and conditions would normally live here. It pads the scroll extent so off-screen estimation has something to measure."; - return ScrollView(VStack(16, [ - Subtitle("Create your benchmark account").AccessibilityView(AccessibilityView.Raw), - .. Fields.Select(field => VStack(6, - Caption(field.Label).AccessibilityView(AccessibilityView.Raw), - field.Secure - ? PasswordBox(ValueOf(field.Key), value => SetValue(field.Key, value)).AccessibilityView(AccessibilityView.Raw) - : TextBox(ValueOf(field.Key), value => SetValue(field.Key, value)).AccessibilityView(AccessibilityView.Raw), - When(submitted && !IsValid(field.Key, ValueOf(field.Key)), () => Body(ErrorOf(field.Key)).Foreground("#b00020").AccessibilityView(AccessibilityView.Raw))) - .Margin(0, 0, 0, 24) - .WithKey(field.Key.ToString())), - Body(filler).TextWrapping().Margin(0, 0, 0, 120).AccessibilityView(AccessibilityView.Raw), - Button("CREATE ACCOUNT", () => - { - setSubmitted(true); - if (Fields.All(field => IsValid(field.Key, ValueOf(field.Key)))) - { - setDone(true); - } - }).HAlign(HorizontalAlignment.Stretch).AccessibilityView(AccessibilityView.Raw), - Body(trailer).TextWrapping().Margin(0, 120, 0, 0).AccessibilityView(AccessibilityView.Raw), - ]).Padding(24)); + return ScrollView( + VStack( + 16, + [ + Subtitle("Create your benchmark account").AccessibilityView(AccessibilityView.Raw), + .. Fields.Select(field => + VStack( + 6, + Caption(field.Label).AccessibilityView(AccessibilityView.Raw), + field.Secure + ? PasswordBox(ValueOf(field.Key), value => SetValue(field.Key, value)) + .AccessibilityView(AccessibilityView.Raw) + : TextBox(ValueOf(field.Key), value => SetValue(field.Key, value)) + .AccessibilityView(AccessibilityView.Raw), + When(submitted && !IsValid(field.Key, ValueOf(field.Key)), () => + Body(ErrorOf(field.Key)) + .Foreground("#b00020") + .AccessibilityView(AccessibilityView.Raw) + ) + ) + .Margin(0, 0, 0, 24) + .WithKey(field.Key.ToString()) + ), + Body(filler).TextWrapping().Margin(0, 0, 0, 120).AccessibilityView(AccessibilityView.Raw), + Button("CREATE ACCOUNT", () => + { + setSubmitted(true); + if (Fields.All(field => IsValid(field.Key, ValueOf(field.Key)))) + { + setDone(true); + } + }) + .HAlign(HorizontalAlignment.Stretch) + .AccessibilityView(AccessibilityView.Raw), + Body(trailer).TextWrapping().Margin(0, 120, 0, 0).AccessibilityView(AccessibilityView.Raw), + ] + ) + .Padding(24) + ); } } diff --git a/apps/WinAppBenchmark/Examples/FlattenedLogin.cs b/apps/WinAppBenchmark/Examples/FlattenedLogin.cs index 24e2337f4..6173e68d2 100644 --- a/apps/WinAppBenchmark/Examples/FlattenedLogin.cs +++ b/apps/WinAppBenchmark/Examples/FlattenedLogin.cs @@ -49,17 +49,25 @@ void Submit() if (loggedIn) { - return VStack(TextBlock("Logged in successfully").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)).Padding(24); + return VStack( + TextBlock("Logged in successfully").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw) + ) + .Padding(24); } - return VStack(12, - Hint($"Use {LoginForm.ValidEmail} / {LoginForm.ValidPassword}").AccessibilityView(AccessibilityView.Raw), - Caption("Email").AccessibilityView(AccessibilityView.Raw), - TextBox(email, setEmail).AccessibilityView(AccessibilityView.Raw), - Caption("Password").AccessibilityView(AccessibilityView.Raw), - PasswordBox(password, setPassword).AccessibilityView(AccessibilityView.Raw), - When(error is not null, () => Body(error!).Foreground("#b00020").AccessibilityView(AccessibilityView.Raw)), - Button("SIGN IN", Submit).AccessibilityView(AccessibilityView.Raw)) + return VStack( + 12, + Hint($"Use {LoginForm.ValidEmail} / {LoginForm.ValidPassword}") + .AccessibilityView(AccessibilityView.Raw), + Caption("Email").AccessibilityView(AccessibilityView.Raw), + TextBox(email, setEmail).AccessibilityView(AccessibilityView.Raw), + Caption("Password").AccessibilityView(AccessibilityView.Raw), + PasswordBox(password, setPassword).AccessibilityView(AccessibilityView.Raw), + When(error is not null, () => + Body(error!).Foreground("#b00020").AccessibilityView(AccessibilityView.Raw) + ), + Button("SIGN IN", Submit).AccessibilityView(AccessibilityView.Raw) + ) .Padding(24); } } diff --git a/apps/WinAppBenchmark/Examples/Gestures.cs b/apps/WinAppBenchmark/Examples/Gestures.cs index 78b8d1c9e..0448e68ce 100644 --- a/apps/WinAppBenchmark/Examples/Gestures.cs +++ b/apps/WinAppBenchmark/Examples/Gestures.cs @@ -38,32 +38,39 @@ void DoubleTapCandidate() Element target = step switch { - 0 => VStack(12, + 0 => VStack( + 12, Hint("Long-press the button below (hold ~1 second)"), Button("Hold me", null) .OnLongPress(() => setStep(1), LongPressDuration, enableMouseEmulation: true) - .AutomationId("long-press-target")), - 1 => VStack(12, + .AutomationId("long-press-target") + ), + 1 => VStack( + 12, Hint("Swipe the card below to the left"), Border(Body("Swipe me left").AutomationId("swipe-target").Padding(24, 32)) .Background(Theme.CardBackground) .WithBorder(Theme.CardStroke) .CornerRadius(12) - .OnPan(_ => { }, onEnded: gesture => - { - if (gesture.Translation.X < SwipeThreshold) + .OnPan( + _ => { }, + onEnded: gesture => { - setStep(2); - } - }, axis: PanAxis.Horizontal)), - _ => VStack(12, + if (gesture.Translation.X < SwipeThreshold) + { + setStep(2); + } + }, + axis: PanAxis.Horizontal + ) + ), + _ => VStack( + 12, Hint("Double-tap the button below"), - Button("Double-tap me", DoubleTapCandidate).AutomationId("double-tap-target")), + Button("Double-tap me", DoubleTapCandidate).AutomationId("double-tap-target") + ), }; - return VStack(16, - Caption($"Step {step + 1} of 3"), - target) - .Padding(24); + return VStack(16, Caption($"Step {step + 1} of 3"), target).Padding(24); } } diff --git a/apps/WinAppBenchmark/Examples/HugeVirtualizedList.cs b/apps/WinAppBenchmark/Examples/HugeVirtualizedList.cs index 7121ccae4..e4b5d06ba 100644 --- a/apps/WinAppBenchmark/Examples/HugeVirtualizedList.cs +++ b/apps/WinAppBenchmark/Examples/HugeVirtualizedList.cs @@ -35,19 +35,27 @@ public override Element Render() columns: [GridSize.Star()], rows: [GridSize.Auto, GridSize.Star()], Hint($"All {TotalRows} rows are loaded. Scroll to {RowLabel(TargetRow)} and tap it.").Padding(16, 12), - ScrollView(ItemsRepeater(Rows, row => row.ToString(), (row, _) => - Button(TextBlock(RowLabel(row)), () => - { - if (row == TargetRow) - { - setFound(true); - } - }) - .AutomationId($"row-{row}") - .Height(RowHeight) - .HAlign(HorizontalAlignment.Stretch) - .CornerRadius(0))) - .AutomationName("Huge list").AutomationId("huge-list") - .Grid(row: 1)); + ScrollView( + ItemsRepeater( + Rows, + row => row.ToString(), + (row, _) => + Button(TextBlock(RowLabel(row)), () => + { + if (row == TargetRow) + { + setFound(true); + } + }) + .AutomationId($"row-{row}") + .Height(RowHeight) + .HAlign(HorizontalAlignment.Stretch) + .CornerRadius(0) + ) + ) + .AutomationName("Huge list") + .AutomationId("huge-list") + .Grid(row: 1) + ); } } diff --git a/apps/WinAppBenchmark/Examples/InfiniteScrollList.cs b/apps/WinAppBenchmark/Examples/InfiniteScrollList.cs index a9ba6b862..2e1393724 100644 --- a/apps/WinAppBenchmark/Examples/InfiniteScrollList.cs +++ b/apps/WinAppBenchmark/Examples/InfiniteScrollList.cs @@ -61,22 +61,30 @@ void ViewChanged() columns: [GridSize.Star()], rows: [GridSize.Auto, GridSize.Star(), GridSize.Auto], Hint($"Scroll down and tap Item {TargetItem} to complete").Padding(16, 12), - ScrollView(ItemsRepeater(items, item => item.ToString(), (item, _) => - Button(TextBlock($"Item {item}"), () => - { - if (item == TargetItem) - { - setFoundTarget(true); - } - }) - .AutomationId($"item-{item}") - .Height(44) - .HAlign(HorizontalAlignment.Stretch) - .CornerRadius(0))) + ScrollView( + ItemsRepeater( + items, + item => item.ToString(), + (item, _) => + Button(TextBlock($"Item {item}"), () => + { + if (item == TargetItem) + { + setFoundTarget(true); + } + }) + .AutomationId($"item-{item}") + .Height(44) + .HAlign(HorizontalAlignment.Stretch) + .CornerRadius(0) + ) + ) .Ref(scroll) .ViewChanged(ViewChanged) - .AutomationName("Items").AutomationId("benchmark-list") + .AutomationName("Items") + .AutomationId("benchmark-list") .Grid(row: 1), - When(loading, () => ProgressRing().AutomationId("list-loading").Padding(12)).Grid(row: 2)); + When(loading, () => ProgressRing().AutomationId("list-loading").Padding(12)).Grid(row: 2) + ); } } diff --git a/apps/WinAppBenchmark/Examples/LoginForm.cs b/apps/WinAppBenchmark/Examples/LoginForm.cs index 2792407a1..4832a5e28 100644 --- a/apps/WinAppBenchmark/Examples/LoginForm.cs +++ b/apps/WinAppBenchmark/Examples/LoginForm.cs @@ -46,23 +46,30 @@ void Submit() if (loggedIn) { - return VStack(16, - Success("Logged in successfully"), - Button("Log out", () => - { - setLoggedIn(false); - setEmail(""); - setPassword(""); - }).AutomationId("logout-button")) + return VStack( + 16, + Success("Logged in successfully"), + Button("Log out", () => + { + setLoggedIn(false); + setEmail(""); + setPassword(""); + }) + .AutomationId("logout-button") + ) .Padding(24); } - return VStack(12, - Hint($"Use {ValidEmail} / {ValidPassword}"), - TextBox(email, setEmail, placeholderText: "Email").AutomationName("Email").AutomationId("email-input"), - PasswordBox(password, setPassword, placeholderText: "Password").AutomationName("Password").AutomationId("password-input"), - When(error is not null, () => Body(error!).Foreground("#b00020").AutomationId("error-message")), - Button("Log in", Submit).AutomationId("login-button")) + return VStack( + 12, + Hint($"Use {ValidEmail} / {ValidPassword}"), + TextBox(email, setEmail, placeholderText: "Email").AutomationName("Email").AutomationId("email-input"), + PasswordBox(password, setPassword, placeholderText: "Password") + .AutomationName("Password") + .AutomationId("password-input"), + When(error is not null, () => Body(error!).Foreground("#b00020").AutomationId("error-message")), + Button("Log in", Submit).AutomationId("login-button") + ) .Padding(24); } } diff --git a/apps/WinAppBenchmark/Examples/ModalFlow.cs b/apps/WinAppBenchmark/Examples/ModalFlow.cs index e736cf85d..e8e2d3312 100644 --- a/apps/WinAppBenchmark/Examples/ModalFlow.cs +++ b/apps/WinAppBenchmark/Examples/ModalFlow.cs @@ -19,17 +19,24 @@ public override Element Render() var (confirmOpen, setConfirmOpen) = UseState(false); var (confirmed, setConfirmed) = UseState(false); - var screen = VStack(12, confirmed - ? Success("Flow completed") - : Button("Open modal", () => setModalVisible(true)).AutomationId("open-modal-button")) + var screen = VStack( + 12, + confirmed + ? Success("Flow completed") + : Button("Open modal", () => setModalVisible(true)).AutomationId("open-modal-button") + ) .Padding(24); - var card = ScrollViewer(VStack(12, - Subtitle("Benchmark modal"), - Body("Tap Continue, then accept the dialog to finish.").TextWrapping(), - Button("Continue", () => setConfirmOpen(true)).AutomationId("continue-button"), - Button("Close", () => setModalVisible(false)).AutomationId("close-modal-button")) - .Padding(20)) + var card = ScrollViewer( + VStack( + 12, + Subtitle("Benchmark modal"), + Body("Tap Continue, then accept the dialog to finish.").TextWrapping(), + Button("Continue", () => setConfirmOpen(true)).AutomationId("continue-button"), + Button("Close", () => setModalVisible(false)).AutomationId("close-modal-button") + ) + .Padding(20) + ) .AutomationId("modal-card") .Background(Theme.CardBackground) .CornerRadius(16, 16, 0, 0) @@ -55,6 +62,7 @@ public override Element Render() setConfirmed(true); } }, - }); + } + ); } } diff --git a/apps/WinAppBenchmark/Examples/ProductCatalog.cs b/apps/WinAppBenchmark/Examples/ProductCatalog.cs index 9a0cb88cc..4d19fbb3c 100644 --- a/apps/WinAppBenchmark/Examples/ProductCatalog.cs +++ b/apps/WinAppBenchmark/Examples/ProductCatalog.cs @@ -17,7 +17,12 @@ public sealed class ProductCatalog : Component private sealed record Product(string Id, string Name, string Size, string Price); - private enum View { List, Detail, Cart } + private enum View + { + List, + Detail, + Cart, + } private static readonly Product[] Products = [ @@ -38,12 +43,15 @@ public override Element Render() var (favorites, setFavorites) = UseState>(new HashSet()); var cartCount = cart.Values.Sum(); - var succeeded = cart.Count == 1 && cart.TryGetValue(TargetId, out var targetQuantity) && targetQuantity == TargetQuantity; + var succeeded = + cart.Count == 1 && cart.TryGetValue(TargetId, out var targetQuantity) && targetQuantity == TargetQuantity; var selected = Products.FirstOrDefault(product => product.Id == selectedId); // Toggles the favorite heart for a product; a decoy interaction that never contributes to the success state. void ToggleFavorite(string id) => - setFavorites(favorites.Contains(id) ? favorites.Where(other => other != id).ToHashSet() : [.. favorites, id]); + setFavorites( + favorites.Contains(id) ? favorites.Where(other => other != id).ToHashSet() : [.. favorites, id] + ); // Adds the currently selected product and quantity to the cart, then returns to the list view. void AddToCart() @@ -61,47 +69,82 @@ void AddToCart() if (view == View.Detail && selected is not null) { - return VStack(12, - Button("‹ Back to catalog", () => setView(View.List)).TextLink().AutomationId("back-to-list"), - Subtitle($"{selected.Name} {selected.Size}"), - Body(selected.Price), - HStack(12, - Button("−", () => setQuantity(Math.Max(1, quantity - 1))).AutomationName("Decrease quantity").AutomationId("quantity-decrease"), - Body(quantity.ToString()).MinWidth(24).VAlign(VerticalAlignment.Center).AutomationId("quantity-value"), - Button("+", () => setQuantity(quantity + 1)).AutomationName("Increase quantity").AutomationId("quantity-increase")), - Button("Add to cart", AddToCart).AutomationId("add-to-cart")) + return VStack( + 12, + Button("‹ Back to catalog", () => setView(View.List)).TextLink().AutomationId("back-to-list"), + Subtitle($"{selected.Name} {selected.Size}"), + Body(selected.Price), + HStack( + 12, + Button("−", () => setQuantity(Math.Max(1, quantity - 1))) + .AutomationName("Decrease quantity") + .AutomationId("quantity-decrease"), + Body(quantity.ToString()) + .MinWidth(24) + .VAlign(VerticalAlignment.Center) + .AutomationId("quantity-value"), + Button("+", () => setQuantity(quantity + 1)) + .AutomationName("Increase quantity") + .AutomationId("quantity-increase") + ), + Button("Add to cart", AddToCart).AutomationId("add-to-cart") + ) .Padding(24); } if (view == View.Cart) { - return VStack(12, [ - Button("‹ Back to catalog", () => setView(View.List)).TextLink().AutomationId("back-to-list"), - Subtitle("Cart"), - When(cartCount == 0, () => Hint("The cart is empty")), - .. Products.Where(product => cart.ContainsKey(product.Id)).Select(product => - Body($"{cart[product.Id]} × {product.Name} {product.Size}").WithKey(product.Id)), - When(succeeded, () => Success("Order ready: 2 × Trail Mix 500 g")), - ]).Padding(24); + return VStack( + 12, + [ + Button("‹ Back to catalog", () => setView(View.List)).TextLink().AutomationId("back-to-list"), + Subtitle("Cart"), + When(cartCount == 0, () => Hint("The cart is empty")), + .. Products + .Where(product => cart.ContainsKey(product.Id)) + .Select(product => + Body($"{cart[product.Id]} × {product.Name} {product.Size}").WithKey(product.Id) + ), + When(succeeded, () => Success("Order ready: 2 × Trail Mix 500 g")), + ] + ) + .Padding(24); } - return ScrollView(VStack(12, [ - Hint($"Add exactly {TargetQuantity} × Trail Mix 500 g to the cart, then review the cart"), - Button($"Cart ({cartCount})", () => setView(View.Cart)).AutomationId("open-cart"), - .. Products.Select(product => HStack(8, - Button(VStack(2, BodyStrong(product.Name), Caption($"{product.Size} · {product.Price}")), () => - { - setSelectedId(product.Id); - setQuantity(1); - setView(View.Detail); - }) - .AutomationName($"{product.Name} {product.Size} {product.Price}") - .AutomationId($"product-{product.Id}") - .Flex(grow: 1), - Button(favorites.Contains(product.Id) ? "♥" : "♡", () => ToggleFavorite(product.Id)) - .AutomationName($"Favorite {product.Name} {product.Size}") - .AutomationId($"favorite-{product.Id}")) - .WithKey(product.Id)), - ]).Padding(24)); + return ScrollView( + VStack( + 12, + [ + Hint($"Add exactly {TargetQuantity} × Trail Mix 500 g to the cart, then review the cart"), + Button($"Cart ({cartCount})", () => setView(View.Cart)).AutomationId("open-cart"), + .. Products.Select(product => + HStack( + 8, + Button( + VStack( + 2, + BodyStrong(product.Name), + Caption($"{product.Size} · {product.Price}") + ), + () => + { + setSelectedId(product.Id); + setQuantity(1); + setView(View.Detail); + } + ) + .AutomationName($"{product.Name} {product.Size} {product.Price}") + .AutomationId($"product-{product.Id}") + .Flex(grow: 1), + Button(favorites.Contains(product.Id) ? "♥" : "♡", () => ToggleFavorite(product.Id)) + .AutomationName($"Favorite {product.Name} {product.Size}") + .AutomationId($"favorite-{product.Id}") + ) + .WithKey(product.Id) + ), + ] + ) + .Padding(24) + ); } } diff --git a/apps/WinAppBenchmark/Examples/SequentialOnboarding.cs b/apps/WinAppBenchmark/Examples/SequentialOnboarding.cs index a0afb3657..e7b5e7425 100644 --- a/apps/WinAppBenchmark/Examples/SequentialOnboarding.cs +++ b/apps/WinAppBenchmark/Examples/SequentialOnboarding.cs @@ -14,7 +14,13 @@ namespace WinAppBenchmark.Examples; /// public sealed partial class SequentialOnboarding : Component { - private enum Step { Email, Name, Phone, Done } + private enum Step + { + Email, + Name, + Phone, + Done, + } [GeneratedRegex(@"^[^\s@]+@[^\s@]+\.[^\s@]+\z")] private static partial Regex EmailPattern(); @@ -49,48 +55,85 @@ void Advance(bool isValid, string message, Step next) if (step == Step.Done) { - return ScrollView(VStack(12, - Success("Onboarding complete"), - Body(email).AutomationId("echo-email"), - Body($"{firstName} {lastName}").AutomationId("echo-name"), - Body(phone).AutomationId("echo-phone")) - .Padding(24)); + return ScrollView( + VStack( + 12, + Success("Onboarding complete"), + Body(email).AutomationId("echo-email"), + Body($"{firstName} {lastName}").AutomationId("echo-name"), + Body(phone).AutomationId("echo-phone") + ) + .Padding(24) + ); } Element fields = step switch { - Step.Email => VStack(12, + Step.Email => VStack( + 12, Caption("Step 1 of 3"), Subtitle("Let's start with your email"), - TextBox(email, setEmail, placeholderText: "e.g. jane@example.com").EmailInput().Ref(focusRef).AutomationName("Email").AutomationId("email-input").WithKey("email")), - Step.Name => VStack(12, + TextBox(email, setEmail, placeholderText: "e.g. jane@example.com") + .EmailInput() + .Ref(focusRef) + .AutomationName("Email") + .AutomationId("email-input") + .WithKey("email") + ), + Step.Name => VStack( + 12, Caption("Step 2 of 3"), Subtitle("Tell us more about you"), Caption("First name"), - TextBox(firstName, setFirstName, placeholderText: "e.g. Jane").Ref(focusRef).AutomationName("First name").AutomationId("first-name-input").WithKey("first-name"), + TextBox(firstName, setFirstName, placeholderText: "e.g. Jane") + .Ref(focusRef) + .AutomationName("First name") + .AutomationId("first-name-input") + .WithKey("first-name"), Caption("Last name").Margin(0, 160, 0, 0), - TextBox(lastName, setLastName, placeholderText: "e.g. Merchant").AutomationName("Last name").AutomationId("last-name-input").WithKey("last-name")), - _ => VStack(12, + TextBox(lastName, setLastName, placeholderText: "e.g. Merchant") + .AutomationName("Last name") + .AutomationId("last-name-input") + .WithKey("last-name") + ), + _ => VStack( + 12, Caption("Step 3 of 3"), Subtitle("Your phone number"), - TextBox(phone, setPhone, placeholderText: "e.g. 0612435678").Ref(focusRef).AutomationName("Phone number").AutomationId("phone-input").WithKey("phone")), + TextBox(phone, setPhone, placeholderText: "e.g. 0612435678") + .Ref(focusRef) + .AutomationName("Phone number") + .AutomationId("phone-input") + .WithKey("phone") + ), }; Action advance = step switch { Step.Email => () => Advance(EmailPattern().IsMatch(email), "Enter a valid email address", Step.Name), - Step.Name => () => Advance(firstName.Trim().Length > 0 && lastName.Trim().Length > 0, "Enter your first and last name", Step.Phone), - _ => () => Advance(PhonePattern().IsMatch(phone), "Enter a 10-digit phone number starting with 0", Step.Done), + Step.Name => () => + Advance( + firstName.Trim().Length > 0 && lastName.Trim().Length > 0, + "Enter your first and last name", + Step.Phone + ), + _ => () => + Advance(PhonePattern().IsMatch(phone), "Enter a 10-digit phone number starting with 0", Step.Done), }; return Grid( columns: [GridSize.Star()], rows: [GridSize.Star(), GridSize.Auto], - ScrollView(fields.Padding(24)).AutomationName($"Onboarding step {step}").AutomationId($"onboarding-step-{step.ToString().ToLowerInvariant()}"), - VStack(8, - When(error is not null, () => Body(error!).Foreground("#b00020").AutomationId("step-error")), - Button("Continue", advance).HAlign(HorizontalAlignment.Stretch).AutomationId("continue-button")) + ScrollView(fields.Padding(24)) + .AutomationName($"Onboarding step {step}") + .AutomationId($"onboarding-step-{step.ToString().ToLowerInvariant()}"), + VStack( + 8, + When(error is not null, () => Body(error!).Foreground("#b00020").AutomationId("step-error")), + Button("Continue", advance).HAlign(HorizontalAlignment.Stretch).AutomationId("continue-button") + ) .Padding(24, 16) - .Grid(row: 1)); + .Grid(row: 1) + ); } } diff --git a/apps/WinAppBenchmark/Examples/StickyChrome.cs b/apps/WinAppBenchmark/Examples/StickyChrome.cs index 430548d28..e9f4cb43f 100644 --- a/apps/WinAppBenchmark/Examples/StickyChrome.cs +++ b/apps/WinAppBenchmark/Examples/StickyChrome.cs @@ -28,38 +28,57 @@ public override Element Render() return VStack(Success("Terms accepted")).Padding(24); } - var sections = Enumerable.Range(1, SectionCount).Select(section => VStack(4, - BodyStrong($"Section {section}"), - Body($"Deterministic agreement paragraph {section} of {SectionCount}. Nothing in this section is actionable; it only adds scroll distance between the top of the screen and the accept button.").TextWrapping()) - .WithKey(section.ToString())); + var sections = Enumerable + .Range(1, SectionCount) + .Select(section => + VStack( + 4, + BodyStrong($"Section {section}"), + Body( + $"Deterministic agreement paragraph {section} of {SectionCount}. Nothing in this section is actionable; it only adds scroll distance between the top of the screen and the accept button." + ) + .TextWrapping() + ) + .WithKey(section.ToString()) + ); - var content = ScrollView(VStack(16, [ - Hint("Read the agreement, tap Accept terms at the bottom, then Continue."), - .. sections, - Button(accepted ? "Terms accepted ✓" : "Accept terms", () => setAccepted(true)).AutomationId("accept-terms"), - ]).Padding(24, 16, 24, 96)); + var content = ScrollView( + VStack( + 16, + [ + Hint("Read the agreement, tap Accept terms at the bottom, then Continue."), + .. sections, + Button(accepted ? "Terms accepted ✓" : "Accept terms", () => setAccepted(true)) + .AutomationId("accept-terms"), + ] + ) + .Padding(24, 16, 24, 96) + ); - var footer = VStack(8, - When(decoyTapped && !accepted, () => Body("Accept the terms at the bottom first").Foreground("#b00020")), + var footer = VStack( + 8, + When(decoyTapped && !accepted, () => + Body("Accept the terms at the bottom first").Foreground("#b00020") + ), Button("Continue", () => - { - if (accepted) { - setDone(true); - } - else - { - setDecoyTapped(true); - } - }).Opacity(accepted ? 1 : 0.5).HAlign(HorizontalAlignment.Stretch).AutomationId("continue-button")) + if (accepted) + { + setDone(true); + } + else + { + setDecoyTapped(true); + } + }) + .Opacity(accepted ? 1 : 0.5) + .HAlign(HorizontalAlignment.Stretch) + .AutomationId("continue-button") + ) .Padding(16) .Background(Theme.SolidBackground) .VAlign(VerticalAlignment.Bottom); - return Grid( - columns: [GridSize.Star()], - rows: [GridSize.Star()], - content, - footer); + return Grid(columns: [GridSize.Star()], rows: [GridSize.Star()], content, footer); } } diff --git a/apps/WinAppBenchmark/Examples/TextInputs.cs b/apps/WinAppBenchmark/Examples/TextInputs.cs index babe61bb2..717b41790 100644 --- a/apps/WinAppBenchmark/Examples/TextInputs.cs +++ b/apps/WinAppBenchmark/Examples/TextInputs.cs @@ -23,14 +23,26 @@ public override Element Render() return VStack(Success("Form submitted")).Padding(24); } - return ScrollView(VStack(8, - Caption("Username (min 3 chars)"), - TextBox(username, setUsername).AutomationName("Username").AutomationId("username-input"), - Caption("PIN (exactly 4 digits, secure)"), - PasswordBox(pin, text => setPin(new string([.. text.Where(char.IsDigit)]))).MaxLength(4).AutomationName("PIN").AutomationId("pin-input"), - Caption($"Notes (multiline, min {MinNotesLength} chars) — {notes.Length}/{MinNotesLength}"), - TextBox(notes, setNotes).AcceptsReturn().TextWrapping().MinHeight(96).AutomationName("Notes").AutomationId("notes-input"), - Button("Submit", () => setSubmitted(true)).IsEnabled(isValid).AutomationId("submit-button")) - .Padding(24)); + return ScrollView( + VStack( + 8, + Caption("Username (min 3 chars)"), + TextBox(username, setUsername).AutomationName("Username").AutomationId("username-input"), + Caption("PIN (exactly 4 digits, secure)"), + PasswordBox(pin, text => setPin(new string([.. text.Where(char.IsDigit)]))) + .MaxLength(4) + .AutomationName("PIN") + .AutomationId("pin-input"), + Caption($"Notes (multiline, min {MinNotesLength} chars) — {notes.Length}/{MinNotesLength}"), + TextBox(notes, setNotes) + .AcceptsReturn() + .TextWrapping() + .MinHeight(96) + .AutomationName("Notes") + .AutomationId("notes-input"), + Button("Submit", () => setSubmitted(true)).IsEnabled(isValid).AutomationId("submit-button") + ) + .Padding(24) + ); } } diff --git a/apps/WinAppBenchmark/Examples/VisionOnly.cs b/apps/WinAppBenchmark/Examples/VisionOnly.cs index 5bf8c2f7e..f303699e4 100644 --- a/apps/WinAppBenchmark/Examples/VisionOnly.cs +++ b/apps/WinAppBenchmark/Examples/VisionOnly.cs @@ -14,7 +14,12 @@ namespace WinAppBenchmark.Examples; /// public sealed class VisionOnly : Component { - private enum Shape { Circle, Square, Diamond } + private enum Shape + { + Circle, + Square, + Diamond, + } private static readonly Shape[] Sequence = [Shape.Square, Shape.Circle, Shape.Diamond]; @@ -41,20 +46,30 @@ void Tap(Shape shape) var done = progress >= Sequence.Length; if (done) { - return VStack(TextBlock("Sequence complete").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw)).Padding(24); + return VStack( + TextBlock("Sequence complete").SemiBold().FontSize(20).AccessibilityView(AccessibilityView.Raw) + ) + .Padding(24); } - return VStack(24, - Body("Tap: square, then circle, then diamond").AccessibilityView(AccessibilityView.Raw), - Body($"Progress: {progress}/{Sequence.Length}{(failed ? " — wrong shape, start over" : "")}").AccessibilityView(AccessibilityView.Raw), - HStack(32, - Ellipse().Fill(Brush("#1565c0")).Size(72, 72).OnTapped((_, _) => Tap(Shape.Circle)), - Rectangle().Fill(Brush("#6a1b9a")).Size(56, 56) - .Set(rectangle => rectangle.CenterPoint = new System.Numerics.Vector3(28, 28, 0)) - .Rotation(45) - .Margin(8) - .OnTapped((_, _) => Tap(Shape.Diamond)), - Rectangle().Fill(Brush("#2e7d32")).Size(72, 72).OnTapped((_, _) => Tap(Shape.Square)))) + return VStack( + 24, + Body("Tap: square, then circle, then diamond").AccessibilityView(AccessibilityView.Raw), + Body($"Progress: {progress}/{Sequence.Length}{(failed ? " — wrong shape, start over" : "")}") + .AccessibilityView(AccessibilityView.Raw), + HStack( + 32, + Ellipse().Fill(Brush("#1565c0")).Size(72, 72).OnTapped((_, _) => Tap(Shape.Circle)), + Rectangle() + .Fill(Brush("#6a1b9a")) + .Size(56, 56) + .Set(rectangle => rectangle.CenterPoint = new System.Numerics.Vector3(28, 28, 0)) + .Rotation(45) + .Margin(8) + .OnTapped((_, _) => Tap(Shape.Diamond)), + Rectangle().Fill(Brush("#2e7d32")).Size(72, 72).OnTapped((_, _) => Tap(Shape.Square)) + ) + ) .Padding(24); } } diff --git a/apps/WinAppBenchmark/GlobalUsings.cs b/apps/WinAppBenchmark/GlobalUsings.cs index f5ad4dec5..13f5b0785 100644 --- a/apps/WinAppBenchmark/GlobalUsings.cs +++ b/apps/WinAppBenchmark/GlobalUsings.cs @@ -3,6 +3,6 @@ global using Microsoft.UI.Reactor; global using Microsoft.UI.Reactor.Core; +global using static Microsoft.UI.Reactor.Factories; global using Microsoft.UI.Reactor.Hooks; global using Microsoft.UI.Xaml; -global using static Microsoft.UI.Reactor.Factories; diff --git a/docs/examples/mobile/DeviceCloudProvider.cs b/docs/examples/mobile/DeviceCloudProvider.cs index 0666f9f8d..07a24d0fb 100644 --- a/docs/examples/mobile/DeviceCloudProvider.cs +++ b/docs/examples/mobile/DeviceCloudProvider.cs @@ -24,10 +24,19 @@ public static class DeviceCloudProvider /// Provider is agent-device's name for the cloud. (.NET-only) makes the leases, so a test /// can stand in for the service. /// - public static IDeviceProvider CloudDevices(CloudDevicesOptions options, Func? leasesFactory = null) + public static IDeviceProvider CloudDevices( + CloudDevicesOptions options, + Func? leasesFactory = null + ) { var leases = (leasesFactory ?? (leaseOptions => new AgentDeviceLeases(leaseOptions)))( - new AgentDeviceLeaseOptions { Provider = options.Provider, Label = options.Provider, StateDir = options.StateDir }); + new AgentDeviceLeaseOptions + { + Provider = options.Provider, + Label = options.Provider, + StateDir = options.StateDir, + } + ); return new CloudDeviceProvider(options, leases); } @@ -44,9 +53,13 @@ public Task AcquireAsync(DeviceRequest request, CancellationToken c Env = new Dictionary(), Summary = request.Platform.WireName(), }, - cancellationToken); + cancellationToken + ); - public Task ReleaseAsync(DeviceLease lease, DeviceReleaseContext context, CancellationToken cancellationToken) => - leases.ReleaseAsync(lease, context, cancellationToken); + public Task ReleaseAsync( + DeviceLease lease, + DeviceReleaseContext context, + CancellationToken cancellationToken + ) => leases.ReleaseAsync(lease, context, cancellationToken); } } diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 000000000..e629905cd --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "1.4.0", + "commands": [ + "csharpier" + ], + "rollForward": false + }, + "husky": { + "version": "0.9.1", + "commands": [ + "husky" + ], + "rollForward": false + } + } +} diff --git a/samples/AcpSample/AcpTodoTests.cs b/samples/AcpSample/AcpTodoTests.cs index 3f05fba10..6b3f33299 100644 --- a/samples/AcpSample/AcpTodoTests.cs +++ b/samples/AcpSample/AcpTodoTests.cs @@ -15,9 +15,13 @@ namespace AcpSample; public sealed class AcpTodoTests : E2ETest { // Built on first use, so a missing adapter fails the test with its own message, not a type initializer error. - private static readonly Lazy Executor = new(() => Environment.GetEnvironmentVariable("ACP_AGENT") == "codex" - ? AcpExecutor.Codex() - : AcpExecutor.ClaudeCode(new AcpAgentOptions { Model = Environment.GetEnvironmentVariable("ACP_MODEL") ?? "sonnet" })); + private static readonly Lazy Executor = new(() => + Environment.GetEnvironmentVariable("ACP_AGENT") == "codex" + ? AcpExecutor.Codex() + : AcpExecutor.ClaudeCode( + new AcpAgentOptions { Model = Environment.GetEnvironmentVariable("ACP_MODEL") ?? "sonnet" } + ) + ); protected override IStepExecutor? AgentExecutor => Executor.Value; diff --git a/samples/E2E.Sample/DaritenTests.cs b/samples/E2E.Sample/DaritenTests.cs index 45902a934..7abe71cc4 100644 --- a/samples/E2E.Sample/DaritenTests.cs +++ b/samples/E2E.Sample/DaritenTests.cs @@ -32,7 +32,9 @@ public async Task An_agent_filters_the_register_by_category() { await App.OpenAsync("/transactions"); await Agent.ActAsync("filter the register to show only the Groceries category"); - await Agent.AssertAsync("every transaction listed is in the Groceries category, or the register says no transactions match"); + await Agent.AssertAsync( + "every transaction listed is in the Groceries category, or the register says no transactions match" + ); await Expect.That(Screen.GetByRole("heading", "Transactions")).ToBeVisibleAsync(); } } diff --git a/samples/E2E.TUnit.Sample/DaritenTests.cs b/samples/E2E.TUnit.Sample/DaritenTests.cs index 9361ad7a3..525a910c0 100644 --- a/samples/E2E.TUnit.Sample/DaritenTests.cs +++ b/samples/E2E.TUnit.Sample/DaritenTests.cs @@ -32,7 +32,9 @@ public async Task An_agent_filters_the_register_by_category() { await App.OpenAsync("/transactions"); await Agent.ActAsync("filter the register to show only the Groceries category"); - await Agent.AssertAsync("every transaction listed is in the Groceries category, or the register says no transactions match"); + await Agent.AssertAsync( + "every transaction listed is in the Groceries category, or the register says no transactions match" + ); await Expect.That(Screen.GetByRole("heading", "Transactions")).ToBeVisibleAsync(); } } diff --git a/samples/E2E.XUnit.V3.Sample/DaritenTests.cs b/samples/E2E.XUnit.V3.Sample/DaritenTests.cs index 66651f9bd..10b3cab60 100644 --- a/samples/E2E.XUnit.V3.Sample/DaritenTests.cs +++ b/samples/E2E.XUnit.V3.Sample/DaritenTests.cs @@ -32,7 +32,9 @@ public async Task An_agent_filters_the_register_by_category() { await App.OpenAsync("/transactions"); await Agent.ActAsync("filter the register to show only the Groceries category"); - await Agent.AssertAsync("every transaction listed is in the Groceries category, or the register says no transactions match"); + await Agent.AssertAsync( + "every transaction listed is in the Groceries category, or the register says no transactions match" + ); await Expect.That(Screen.GetByRole("heading", "Transactions")).ToBeVisibleAsync(); } } diff --git a/samples/MobileApp.E2ETests/DeviceTests.cs b/samples/MobileApp.E2ETests/DeviceTests.cs index c17ce0061..301ea732e 100644 --- a/samples/MobileApp.E2ETests/DeviceTests.cs +++ b/samples/MobileApp.E2ETests/DeviceTests.cs @@ -23,7 +23,10 @@ public async Task The_agent_counts_taps() [Test] public async Task Keeps_the_count_after_the_app_goes_to_the_background() { - Assume.That(!AttachesToRunningApp, "The DevFlow agent runs inside the app and cannot send it to the background."); + Assume.That( + !AttachesToRunningApp, + "The DevFlow agent runs inside the app and cannot send it to the background." + ); await Screen.GetByTestId("increment").TapAsync(); await Expect.That(Screen.GetByTestId("counter")).ToHaveTextAsync("Count: 1"); @@ -51,10 +54,10 @@ public async Task Works_in_dark_mode() await Device.SetAppearanceAsync(Appearance.Dark); try { - await Agent.ActAsync("get the app to greet {name}", new ActOptions - { - Params = new Dictionary { ["name"] = "Linus" }, - }); + await Agent.ActAsync( + "get the app to greet {name}", + new ActOptions { Params = new Dictionary { ["name"] = "Linus" } } + ); await Expect.That(Screen.GetByTestId("greeting")).ToHaveTextAsync("Hello, Linus!"); } diff --git a/samples/MobileApp.E2ETests/GreetingTests.cs b/samples/MobileApp.E2ETests/GreetingTests.cs index d530f08ab..7847d4d36 100644 --- a/samples/MobileApp.E2ETests/GreetingTests.cs +++ b/samples/MobileApp.E2ETests/GreetingTests.cs @@ -36,10 +36,10 @@ public async Task Greets_the_name_you_type() public async Task The_agent_gets_a_greeting() { // The agent works out which field and button to use. - await Agent.ActAsync("get the app to greet {name}", new ActOptions - { - Params = new Dictionary { ["name"] = "Grace" }, - }); + await Agent.ActAsync( + "get the app to greet {name}", + new ActOptions { Params = new Dictionary { ["name"] = "Grace" } } + ); // Each agent step is paired with a check that does not call the model. await Expect.That(Screen.GetByTestId("greeting")).ToHaveTextAsync("Hello, Grace!"); diff --git a/samples/MobileApp/App.xaml b/samples/MobileApp/App.xaml index 79393930a..8eb840cb5 100644 --- a/samples/MobileApp/App.xaml +++ b/samples/MobileApp/App.xaml @@ -1,14 +1,16 @@  - - - - - - - - - + + + + + + + + + diff --git a/samples/MobileApp/App.xaml.cs b/samples/MobileApp/App.xaml.cs index 64eea7061..5b5e0030a 100644 --- a/samples/MobileApp/App.xaml.cs +++ b/samples/MobileApp/App.xaml.cs @@ -4,13 +4,13 @@ namespace MobileApp; public partial class App : Application { - public App() - { - InitializeComponent(); - } + public App() + { + InitializeComponent(); + } - protected override Window CreateWindow(IActivationState? activationState) - { - return new Window(new AppShell()); - } -} \ No newline at end of file + protected override Window CreateWindow(IActivationState? activationState) + { + return new Window(new AppShell()); + } +} diff --git a/samples/MobileApp/AppShell.xaml b/samples/MobileApp/AppShell.xaml index 7e135e86b..e503989cd 100644 --- a/samples/MobileApp/AppShell.xaml +++ b/samples/MobileApp/AppShell.xaml @@ -1,14 +1,10 @@ - - - + x:Class="MobileApp.AppShell" + xmlns="http://schemas.microsoft.com/dotnet/2021/maui" + xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" + xmlns:local="clr-namespace:MobileApp" + Title="MobileApp" +> + diff --git a/samples/MobileApp/AppShell.xaml.cs b/samples/MobileApp/AppShell.xaml.cs index 84f7717fc..0d5a1bb1b 100644 --- a/samples/MobileApp/AppShell.xaml.cs +++ b/samples/MobileApp/AppShell.xaml.cs @@ -2,8 +2,8 @@ public partial class AppShell : Shell { - public AppShell() - { - InitializeComponent(); - } + public AppShell() + { + InitializeComponent(); + } } diff --git a/samples/MobileApp/MainPage.xaml b/samples/MobileApp/MainPage.xaml index e16866c51..bd8166b9f 100644 --- a/samples/MobileApp/MainPage.xaml +++ b/samples/MobileApp/MainPage.xaml @@ -1,60 +1,50 @@ - - - - -