diff --git a/.claude/skills/forma-testing/SKILL.md b/.claude/skills/forma-testing/SKILL.md index 598f9a61e..78ef887d6 100644 --- a/.claude/skills/forma-testing/SKILL.md +++ b/.claude/skills/forma-testing/SKILL.md @@ -52,6 +52,7 @@ A test that passes alone and fails under load is broken, not unlucky: its assert - Do await the handler's own task, from `ClickAsync` or `TriggerEventAsync`, where the component's work passes through a library that awaits with `ConfigureAwait(false)`; that work leaves the renderer, and nothing done on the renderer can wait for it. - Do give a component a contract to inject, as `IEmojiSpriteLoader` beside `EmojiSpriteLoader`, when a test needs to hold its work and the only way in was a pending script call. - Don't wait on the clock for a completion the test controls: no `WaitForAssertion` or `WaitForState` after completing a gate, no `Task.Delay`, and never a widened timeout or a retry, which hide the race rather than remove it. +- Do wait in the page, with `WaitForFunctionAsync` reading the DOM, for a state a browser check's page of hundreds of items has yet to reach, and assert once it has. An assertion that finds its state not yet reached describes the element it reads on every poll, the whole view on such a page, which holds the page from drawing the answer it waits for, for seconds in WebKit under load. - Do prove a fix under the conditions that failed, repeating the project while something else loads the machine, before calling the test stable. ## JavaScript tests diff --git a/.github/workflows/full.yml b/.github/workflows/full.yml index 53927ce1b..bbf4a7b26 100644 --- a/.github/workflows/full.yml +++ b/.github/workflows/full.yml @@ -1,5 +1,6 @@ # Runs the full gate on every platform a release is held to: Linux's and Windows' gates, -# WebView2 among Windows', and Android's checks on an emulator, the components in its web view and the MAUI example; +# WebView2 among Windows', Android's checks on an emulator, the components in its web view and the MAUI example, and +# every component's early runs on Linux; # it builds the MAUI example for iOS and Mac Catalyst as well, and reports those builds without holding a release to them, # and it checks every package the repository depends on against the advisories as they stand when it runs. # A push to candidate runs it on the candidate, whose run a promotion to main and a release require to have passed for @@ -417,14 +418,12 @@ jobs: if-no-files-found: ignore retention-days: 14 - # Every component's early runs, its Forma scripts held while the check acts. The job is reported: a failure holds - # nothing, and its results are kept under a name the nightly report doesn't file. + # Every component's early runs, its Forma scripts held while the check acts. early: name: components early needs: commit runs-on: ubuntu-latest timeout-minutes: 150 - continue-on-error: true steps: - uses: actions/checkout@v7 @@ -440,11 +439,16 @@ jobs: - name: Check the components' early runs run: pwsh ./scripts/build/browser.ps1 -Early -Filter 'Runtime=server-early|Runtime=webassembly-early' + - name: Note the job's failure + if: failure() || cancelled() + shell: pwsh + run: New-Item -ItemType File -Force -Path 'artifacts/browser/results/job-failed' | Out-Null + - name: Keep the checks' results if: always() uses: actions/upload-artifact@v7 with: - name: early-checks-linux-1 + name: checks-early-linux-1 path: artifacts/browser/results if-no-files-found: ignore retention-days: 14 @@ -453,7 +457,7 @@ jobs: # filed as an issue, an unreachable device as one, and a job that failed outside its checks as one of its own. report: name: report - needs: [commit, dependencies, gate, mobile, android] + needs: [commit, dependencies, gate, mobile, android, early] # A run cancelled as a whole files nothing; a job of it that ran out of time is reported as failed. if: always() && !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 79c5cd1ac..62a950c51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ release is cut, and reads *Unreleased* until then. It lists every change a consu breaks what the release before it allowed says how to migrate, as [Versioning's rules](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.5/docs/releases.md#the-release-record) set out. What Forma gained before its first release, month by month, is in [the feature history](FEATURE-HISTORY.md). +## `1.0.0-preview.25` + +*December 2, 2026* + +- A wheel turned or a swipe made over a `FormaDataView` that grows with its page scrolls the page, and so does one + over a `FormaExplorer` flowing in a phone's page, where in Chromium the page stayed put. Over a view or an explorer + that scrolls within a height of its own, a turn or a swipe past the end of its items goes on to the page. + ## `1.0.0-preview.24` *December 1, 2026* diff --git a/Directory.Build.props b/Directory.Build.props index 9b1ba727e..30ac97ed7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -27,7 +27,7 @@ 1.0.0 - preview.24 + preview.25 diff --git a/Forma.slnx b/Forma.slnx index 5d68b3d89..80d5e7d11 100644 --- a/Forma.slnx +++ b/Forma.slnx @@ -96,6 +96,7 @@ + diff --git a/README.md b/README.md index b985caf5d..a1d4d973c 100644 --- a/README.md +++ b/README.md @@ -408,7 +408,11 @@ shows. Interactive, it switches the page at each change; rendered statically, it is a form whose Apply button posts the choice to `MapFormaThemes()`, so a reader with no script running still switches. For a menu, such as a header's, its `Layout` of `ThemePickerLayout.Buttons` offers each theme and each scheme as a button that applies its choice as it's pressed, -statically too, the choice in force pressed. +statically too, the choice in force pressed. A statically rendered picker's forms carry an antiforgery token only where +the application validates tokens, so where it checks a post by where it comes from instead, a page carrying the picker +can be kept for every reader, as [the server half's +README](https://github.com/FormaUI/Forma/blob/main/src/Framework/Forma.Framework.Themes.Blazor.Server/README.md#caching-pages) +sets out. ```razor @using Forma.Blazor.Components.Themes diff --git a/docs/data-view-design.md b/docs/data-view-design.md index d8b49f13a..90e4fff94 100644 --- a/docs/data-view-design.md +++ b/docs/data-view-design.md @@ -356,7 +356,8 @@ The items live in a scroll region the engine owns, with what a view pins, the gr header, stuck to its top and the footer outside it. The data view caps itself at the height it is given: against an auto-height ancestor the cap resolves to none and the view takes the height of its items, and inside a bounded shell the items scroll while the pinned -parts and the footer stay put. A paged data view holds its region at the height of a full +parts and the footer stay put. A turn of the wheel or a swipe the region can't take, over +items growing with the page or past the end of items that scroll, goes on to the page. A paged data view holds its region at the height of a full page while another page is known to exist, so a short last page does not shrink it: its count runs past one page, its source says it holds more, or a page comes before the one shown. A set known to fit one page diff --git a/docs/explorer-design.md b/docs/explorer-design.md index 417fd55d0..920859a7a 100644 --- a/docs/explorer-design.md +++ b/docs/explorer-design.md @@ -148,7 +148,7 @@ activated, and in the selection mode a press or Space checks its box while Enter opens it, the focus staying on its item as the mode changes. On a phone the explorer has no height of its own, so its items are the page's own list rather -than a box that scrolls inside the page. A phone is a viewport under 40rem wide, or under +than a box that scrolls inside the page, a swipe over them scrolling the page. A phone is a viewport under 40rem wide, or under 40rem tall beneath a coarse pointer, too short for a box of 40rem beside the page around it. An infinite scroll appends each page as the page nears the list's end, and its header stays at the top of what scrolls them, `--forma-explorer-header-inset-block-start` below a host's own diff --git a/docs/features-status.md b/docs/features-status.md index 7905e7ac3..ad47ae94e 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -7,7 +7,7 @@ | Measure | Now | | --- | --- | | Components | 83 implemented, as [the catalog](component-catalog.md) lists them, and 21 planned, as [the roadmap](component-roadmap.md) orders them | -| Packages | Every project under `src/` but the Showcase, released from `main` by `release.yml` to nuget.org and the organization's GitHub feed, the latest published release `1.0.0-preview.24` | +| Packages | Every project under `src/` but the Showcase, released from `main` by `release.yml` to nuget.org and the organization's GitHub feed, the latest published release `1.0.0-preview.25` | | Render modes | Interactive Server, WebAssembly and Auto implemented: every call a component makes to a script and every call back checked in each, and on the Server in WebKit, the engine of Safari and of Apple's web views, every runtime on a page following its culture coordinator, a client reading its host's own strings, and a host setting either arrangement up as the README says; static rendering implemented, every check page rendered statically with no enabled control that needs interactivity; Blazor Hybrid implemented on WPF, Windows Forms and MAUI on Windows, every component checked in a web view and each host's application set up as the README says; an inventory holds every component to a check page in every render mode | The gate runs every check [the verification design](verification-design.md#gates) sets out, each platform's where the machine can run it. It passes locally on Windows and in CI on Linux, on Windows and on an Android emulator. @@ -27,11 +27,10 @@ The gate runs every check [the verification design](verification-design.md#gates | [The build](#the-build) | Faster tests, a faster gate, builds in processes of their own and the examples' locale lint; the affected-checks command next | | [The input router's host routes](#the-input-routers-host-routes) | Installed on every interactive page with a Forma component | | [A host's integration](#a-hosts-integration) | Fifteen findings, all fixed | -| [A host's requests](#a-hosts-requests) | Four components implemented and one on the roadmap, and thirty changes, all fixed | +| [A host's requests](#a-hosts-requests) | Four components implemented and one on the roadmap, thirty-one changes fixed, and one already met | | [A security check](#a-security-check) | Every step in place | | [Themes](#themes) | Steps 1 to 11 landed, and 12 and 13 on every platform but iOS and Mac Catalyst, which wait on a Mac | | [The Showcase's review modes](#the-showcases-review-modes) | Planned, nine steps open, the pointer emulation's prototype and the preview first | -| [Early runs](#early-runs) | The early runs reported and passing, required once a candidate passes them | - **One component at a time,** built, reviewed and approved before the next starts, as the working rules in `CLAUDE.md` set out. - **A change is a commit,** each passing its own checks, and the full gate runs at integration and release, as [the verification design](verification-design.md#gates) sets out. @@ -118,6 +117,7 @@ Each feature, the document that states it, its state, and the month it first lan | --- | --- | --- | --- | | The gate and CI on Linux and Windows | [Build and verification](repository-structure.md#build-and-verification) | Implemented, Android's checks in [the environment the repository declares](repository-structure.md#the-android-environment), its JDK and its emulator, on every machine and in CI alike | [September 2026](../FEATURE-HISTORY.md#2026-09) | | The browser check | [Tests](repository-structure.md#tests) | Implemented | [October 2026](../FEATURE-HISTORY.md#2026-10) | +| The early runs: every component checked as a reader meets it on a page still loading, its scripts held back | [Verification design](verification-design.md#early-runs) | Implemented, required of every full run in CI | [`1.0.0-preview.24`](../CHANGELOG.md#100-preview24) | | The Showcase's review modes: a page in each device, pointer, theme, scheme and direction, and side by side | [Showcase design](showcase-design.md) | [Planned](#the-showcases-review-modes) | — | | The screen reader check | [Screen reader checks design](screen-reader-checks-design.md) | Implemented | [October 2026](../FEATURE-HISTORY.md#2026-10) | | Releases | [Build and verification](repository-structure.md#build-and-verification) | Implemented: each release published from its signed tag on `main` to nuget.org and the organization's GitHub feed, and proven against what it published: a consumer outside the repository reading a locale pack it restored from a feed into an empty cache, and a project outside it declaring `IsLocalePack` packing as a pack | [September 2026](../FEATURE-HISTORY.md#2026-09) | @@ -222,7 +222,7 @@ Reviewing a host's integration against Forma's source turned up fifteen findings A host's list of what it needs from Forma named five components Forma lacked: `FormaComboBox`, `FormaLinkTabs`, `FormaLineChart` and `FormaBarChart`, all now implemented, as [the catalog](component-catalog.md) lists them, and `FormaRadioGroup`, which [the roadmap](component-roadmap.md) builds first. It named a search of its commands too, which -`FormaCommandPalette` is, and thirty changes to components that exist, listed here in the order they are taken, +`FormaCommandPalette` is, and thirty-two changes to components that exist, listed here in the order they are taken, each with what the code does and its state. | Request | What the code does | State | @@ -257,6 +257,8 @@ each with what the code does and its state. | A toast's action | `IToastService.ShowAsync` took a message, a type and a duration, so a toast couldn't lead to what it announces, such as the request it says was sent. It takes a `ToastAction` now, a label with an address or a callback, drawn as a button within the toast's live region, and a toast with one stays until it's dismissed or its action is used | Fixed | | A tag left open in sanitized markup | `AllowlistHtmlSanitizer` copied a `<` that opened no complete tag as typed, so a rich text ending in a tag never closed, such as a `meta` refresh, reached the page whole and took the page's own markup after it as its end, keeping every attribute the policy refuses. It writes such a `<` as `<` now, so the tag stays text | Fixed | | A theme picker at one press | `FormaThemePicker` drawn statically was a form of lists with an Apply button, so in a header's menu a reader chose and then applied. Its `ThemePickerLayout.Buttons` offers each theme and each scheme as a button that applies its choice as it's pressed, posted from a static page and switched in place on an interactive one, the choice in force pressed and checked | Fixed | +| A theme picker on a page kept for every reader | `FormaThemePicker` drawn statically writes into each form the antiforgery token its request generates, and ASP.NET Core generates one only where the application calls `UseAntiforgery()`. In an application relying on its check of where a post comes from, by the Fetch Metadata a browser sends, the forms carry no token, so a page carrying the picker sets no cookie and can be kept for every reader, and `MapFormaThemes()` takes their posts from the application's own pages and refuses another site's. [The theme design](theme-design.md#a-statically-rendered-pickers-posts) and the server half's README say so, and the picker's and the endpoint's tests hold them to it | Already met | +| The page's scroll over a data view | `FormaDataView`'s region, and the explorer's media and folder tree, contained their overscroll, which in Chromium ends a wheel's or a swipe's scroll at the box whether or not it has anything to scroll, so over a view growing with its page, or an explorer flowing in a phone's, the page didn't scroll. None contains it now, so a turn or a swipe the box can't take goes on to the page, as it does over the rest of the page | Fixed | @@ -314,19 +316,6 @@ review bar, the device view, the pointer emulation, and direction and comparison window's theme picker and the Themes page follow, each waiting on the theme plan's steps it names. None of the steps has landed. - - -## Early runs - -[The verification design's early runs](verification-design.md#early-runs) check each component as a reader meets it on -a page still loading, its scripts held back while the check presses and types. [The verification implementation -plan](verification-implementation-plan.md) carries them out in three steps: the early runs, reported at first; a sweep -fixing every component they fail; and the early runs required. No release is cut until the sweep is done, unless a host -is blocked on a fix. The early runs have landed, reported by a job of the full gate that holds nothing, and the sweep is -done: every component's early runs pass, a component drawing a control whose script hasn't attached as a static render -draws it, as [render modes](component-foundations-design.md#render-modes) sets out, and a check of a gesture skipping -its early runs. The early runs become required once a candidate's full run passes them clean. - ## Deferred @@ -338,4 +327,5 @@ Each waits for the trigger named beside it before its design or its implementati | Observing the document's child list | No consumer needs it, and its cost is unmeasured | A consumer with a measured cost | | Growing the DOM watcher and engine's design beyond its plan | Its plan's steps come first | Those steps landed | | A System preference following the device's `prefers-contrast` | Forma High Contrast is chosen explicitly first, as [the theme design](theme-design.md#light-dark-and-high-contrast) sets out | The theme system in use | +| A theme picker without its token where the application validates antiforgery tokens | A page kept for every reader already carries the picker without a token in an application checking where a post comes from, as [the theme design](theme-design.md#a-statically-rendered-pickers-posts) sets out; one validating tokens would need `MapFormaThemes()` to check a post without a token by where it comes from instead | A host validating antiforgery tokens that keeps a page carrying the picker for every reader | | The device view as a component for hosts | It serves the Showcase's review alone, as [the Showcase design](showcase-design.md#where-the-parts-live) sets out | A host's concrete need | diff --git a/docs/theme-design.md b/docs/theme-design.md index d187be9a7..a5c5f1874 100644 --- a/docs/theme-design.md +++ b/docs/theme-design.md @@ -486,6 +486,19 @@ Either way, the picker switches the page however the page is rendered: with no script running still switches. A store that fails leaves the cookie holding the choice beside the earlier revision, so the browser draws the new choice and the store keeps its earlier one. +### A statically rendered picker's posts + +The endpoint takes a post as the application checks every form it reads, and the picker's forms carry what that +check reads. An application checks a form in one of two ways: + +- **By where it comes from.** ASP.NET Core reads the Fetch Metadata a browser sends in an application that validates + no antiforgery tokens. The application generates no token, so the picker's forms carry none, and the endpoint takes a + post from the application's own pages and refuses one from another site. The picker sets no cookie, so a host can + keep a page carrying it and serve it to every reader, once for each choice. +- **By an antiforgery token.** An application validating tokens generates one for each request, and each of the + picker's forms carries it. A token is one reader's, so there a page carrying the picker is never kept for every + reader. + ## A part in a theme of its own `FormaThemeScope` draws its content in a theme, a scheme, or both, of its own, whatever its surroundings': diff --git a/docs/verification-design.md b/docs/verification-design.md index 5740297be..3e474a158 100644 --- a/docs/verification-design.md +++ b/docs/verification-design.md @@ -2,8 +2,7 @@ Forma's code is checked by tests of five kinds, run by two gates. This design states what each kind proves, where its suites live and what they are named, where the helpers they share live, which gate runs what and -when, and how a commit is promoted from the integrated work to a release. [The implementation -plan](verification-implementation-plan.md) holds the steps that carry out its early runs. +when, and how a commit is promoted from the integrated work to a release. ## Kinds of test @@ -105,10 +104,11 @@ failed, so a fix to a host's startup reaches both. among it. It runs every check the machine it runs on can execute, naming each platform check it couldn't, as WebView2's away from Windows or Android's where the Android environment the repository declares isn't installed. Android's checks run in that environment alone, its JDK and its emulator, on every machine and in CI alike. A full - run in CI passes only once every required platform job has passed for the same SHA: Linux's, Windows' with - WebView2, and Android's E2E. The MAUI example's builds for iOS and Mac Catalyst, on a hosted Mac, are reported - beside them and hold nothing. A local full run leaves each required platform it names as one it couldn't run to CI's - full run of the same SHA, which promotion waits for. The nightly run on `dev` holds the same coverage as a candidate's. + run in CI passes only once every required job has passed for the same SHA: Linux's, Windows' with WebView2, + Android's E2E, and the components' early runs on Linux. The MAUI example's builds for iOS and Mac Catalyst, on a + hosted Mac, are reported beside them and hold nothing. A local full run leaves each required platform it names as one + it couldn't run to CI's full run of the same SHA, which promotion waits for. The nightly run on `dev` holds the same + coverage as a candidate's. ### What a change runs @@ -190,10 +190,13 @@ out, and a text a field took before its edits listened reaches the component onc reader can't see it. Since the page's scripts start as the check acts, what a check expects is waited for as long as a script's first answer is. - **Where it runs.** A change's development gate runs the early runs of the components in its affected set, and the full - gate runs every component's. + gate runs every component's, in a job a full run in CI requires as it requires each platform's. A component losing + what a reader did before its script listened is caught in the gate, before a release, rather than by a host after one. - **What a failure means.** A check failing in its early run alone is a component that showed a control as ready before its script could answer it, or lost or misread a text the reader typed before its edits listened. It's fixed in the component, with a component test holding the same script, never with a wait for the script in the check. + Every early run writes to its check's output when the page took its first input, when its scripts were released and + which were still loading as the page closed, so a failure shows where the page stood. - **What can't run early.** A gesture, a drag, a drop or a wheel turn, goes to the script listening as it begins, so a check of one skips its early runs. So does a check standing in for the browser with an event only a listener hears, as an autofill's animation, since what the browser did earlier reaches the script through the element's own state, diff --git a/docs/verification-implementation-plan.md b/docs/verification-implementation-plan.md deleted file mode 100644 index 8f12c00e8..000000000 --- a/docs/verification-implementation-plan.md +++ /dev/null @@ -1,31 +0,0 @@ -# Forma Verification Implementation Plan - -The steps that carry out [the verification design's early runs](verification-design.md#early-runs), in order, each -landing with its tests and its gate. They close one family of defect, a component losing or misreading what the reader -did before its script listened, in the gate rather than one instance at a time after a release. - -## Steps - -1. ✅ **The early runs.** The `server-early` and `webassembly-early` runtimes beside the component checks' others, the - scripts held and released as the design sets out, the waits for a component's script returning at once while they're - held, `browser.ps1 -Early` running them, and a job of the full gate running them for every component. The job is - reported and holds nothing until step 3. -2. ✅ **The sweep.** Every component's early runs, each failure fixed in its component as the design says, with a component - test holding the same script, one commit for each fix. No release is cut until the sweep is done, unless a host is - blocked on a fix. - - The first sweep ran 520 early checks and failed 107. Most are a key or a press a component took before its script - registered with the input router: the data view's selection and focus, the tree's keys, the sortable list's arrow - key and the toolbar's shortcuts. The rest are the composer's typing, dialogs and transfers, and gestures begun - before the script listened: drags, drops and wheel turns. - - Two checks read the input router through a wait an early run skips. They now wait through helpers that load it. - - A component draws a control whose script hasn't attached as a static render draws it, as [render - modes](component-foundations-design.md#render-modes) sets out, in place of an input router holding what the reader - did for a scope still to register: the sortable list's handles, the data view's busy region, the tree, the rich - text canvas and a toolbar action whose shortcut isn't registered yet. Their checks wait for what a reader sees, - and a check of a drag, a drop or a wheel turn skips its early runs. - - The hold stops routing a page's scripts once it releases them. Routed through the check, a released page's modules - loaded one import after another seconds late under a full run's load, past a check's own waits. - - The last sweep ran the 520 early checks clean, the 24 a gesture or an autofill's stand-in drives skipping. -3. **The early runs required.** Once a candidate's full run passes them clean, the full gate's early job is required, so - promotion waits for it as for every other required job, and the nightly report files its failures as it files the - other jobs'. diff --git a/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.css b/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.css index aba936da7..e46fe3403 100644 --- a/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.css +++ b/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.css @@ -21,7 +21,6 @@ flex: 1 1 auto; min-block-size: 0; overflow: auto; - overscroll-behavior: contain; } /* A companion view stands at the inline start with the active view beside it. */ diff --git a/src/Blazor/Forma.Blazor.Explorer/FormaExplorerContentArea.razor.css b/src/Blazor/Forma.Blazor.Explorer/FormaExplorerContentArea.razor.css index fecffb43b..0d8923158 100644 --- a/src/Blazor/Forma.Blazor.Explorer/FormaExplorerContentArea.razor.css +++ b/src/Blazor/Forma.Blazor.Explorer/FormaExplorerContentArea.razor.css @@ -19,7 +19,6 @@ flex: 1; min-block-size: 0; overflow: auto; - overscroll-behavior: contain; scrollbar-width: thin; } diff --git a/src/Blazor/Forma.Blazor.Explorer/FormaExplorerSidebar.razor.css b/src/Blazor/Forma.Blazor.Explorer/FormaExplorerSidebar.razor.css index 5a815a8a6..e4d3fb198 100644 --- a/src/Blazor/Forma.Blazor.Explorer/FormaExplorerSidebar.razor.css +++ b/src/Blazor/Forma.Blazor.Explorer/FormaExplorerSidebar.razor.css @@ -24,7 +24,6 @@ max-block-size: 30rem; overflow-y: auto; overflow-x: hidden; - overscroll-behavior: contain; scrollbar-width: thin; border-block-end: 1px solid var(--border-color); } diff --git a/src/Framework/Forma.Framework.Localization/README.md b/src/Framework/Forma.Framework.Localization/README.md index 155d91cc4..f2c8855ab 100644 --- a/src/Framework/Forma.Framework.Localization/README.md +++ b/src/Framework/Forma.Framework.Localization/README.md @@ -368,7 +368,7 @@ and referencing this package, whose build does the rest: - + diff --git a/src/Framework/Forma.Framework.Themes.Blazor.Server/README.md b/src/Framework/Forma.Framework.Themes.Blazor.Server/README.md index 6d335a123..65d6a1e0f 100644 --- a/src/Framework/Forma.Framework.Themes.Blazor.Server/README.md +++ b/src/Framework/Forma.Framework.Themes.Blazor.Server/README.md @@ -25,7 +25,6 @@ var app = builder.Build(); app.UseFormaThemes(); app.UseRouting(); -app.UseAntiforgery(); app.MapStaticAssets(); app.MapFormaThemes(); @@ -81,12 +80,20 @@ record and reads no store, and its theme marker says so. `MapFormaThemes()` takes a switch at `/_forma/themes`, which `FormaThemePicker` posts where it is rendered statically, and any form of the application's own can post too. The form posts `theme`, a registered theme's name, `scheme`, -`system`, `light` or `dark`, and `returnUrl`, an address of the application's own, with the antiforgery token the -application validates. The endpoint keeps the choice in the store first, one revision past the latest it knows of, then -in the record with that revision, and sends the reader back. A store that fails leaves the record holding the choice -beside the earlier revision, so the browser draws the new choice and the store keeps its earlier one. A form naming no -registered theme or no scheme preference is refused with 400, and a return address that isn't the application's own -sends the reader to its root. +`system`, `light` or `dark`, and `returnUrl`, an address of the application's own. The endpoint keeps the choice in the +store first, one revision past the latest it knows of, then in the record with that revision, and sends the reader +back. A store that fails leaves the record holding the choice beside the earlier revision, so the browser draws the new +choice and the store keeps its earlier one. A form naming no registered theme or no scheme preference is refused with +400, and a return address that isn't the application's own sends the reader to its root. + +The endpoint takes a post as ASP.NET Core checks every form an application reads, in one of two ways: + +- **By where the post comes from,** in an application built with `WebApplication` that doesn't call + `UseAntiforgery()`. ASP.NET Core reads the Fetch Metadata the browser sends, so the endpoint takes a post from the + application's own pages and refuses one another site sends with 400. The application generates no antiforgery token, + so the picker's forms carry none. +- **By an antiforgery token,** in an application that calls `UseAntiforgery()`. Each of the picker's forms carries the + token its request generates, and the endpoint refuses a post without a valid one with 400. ## Caching pages @@ -97,6 +104,10 @@ page: builder.Services.AddOutputCache(options => options.AddBasePolicy(policy => policy.VaryByFormaTheme())); ``` +A page carrying a statically rendered picker is cached only where the application checks a post by where it comes +from. An antiforgery token is one reader's: generating it sets the antiforgery cookie and marks the response not to be +kept, so a page carrying one isn't cached. + ## License Apache License 2.0, under the repository's [`LICENSE`](https://github.com/FormaUI/Forma/blob/main/LICENSE). diff --git a/src/Framework/Forma.Framework.Themes.Blazor.Server/ThemeApplicationBuilderExtensions.cs b/src/Framework/Forma.Framework.Themes.Blazor.Server/ThemeApplicationBuilderExtensions.cs index 45ef4eda0..907143232 100644 --- a/src/Framework/Forma.Framework.Themes.Blazor.Server/ThemeApplicationBuilderExtensions.cs +++ b/src/Framework/Forma.Framework.Themes.Blazor.Server/ThemeApplicationBuilderExtensions.cs @@ -31,7 +31,8 @@ public static IApplicationBuilder UseFormaThemes(this IApplicationBuilder app) /// Maps the endpoint a statically rendered theme picker posts a switch to: it keeps the choice in the host's store, then in the browser's record, and sends the reader back to the page. /// /// The form carries theme, a registered theme's name, scheme, system, light or dark, and - /// returnUrl, an address of the application's own, along with the antiforgery token the application validates. The + /// returnUrl, an address of the application's own, and is checked as the application checks every form it reads: by its + /// antiforgery token where the application validates tokens, and otherwise by where the browser says it came from. The /// store is written first, one revision past the latest the request knows of, and the record with that revision; a store /// that fails leaves the record holding the choice beside the earlier revision, so the browser draws the new choice and the /// store keeps its earlier one. diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Themes/FormaThemePickerTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Themes/FormaThemePickerTests.razor index f9bad7ec3..4b44a6d67 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Themes/FormaThemePickerTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Themes/FormaThemePickerTests.razor @@ -18,6 +18,16 @@ } } + // The antiforgery token the request generates, or none, as for an application that validates no tokens. + private sealed class FakeAntiforgeryStateProvider(AntiforgeryRequestToken? token) : AntiforgeryStateProvider + { + public override AntiforgeryRequestToken? GetAntiforgeryToken() + => token; + } + + private static FakeAntiforgeryStateProvider CreateTokenProvider() + => new(new AntiforgeryRequestToken("request-token", "__RequestVerificationToken")); + public sealed class Component { [Fact] @@ -66,6 +76,52 @@ Assert.Equal("/he/theme-picker/static?section=1", cut.Find("input[name=returnUrl]").GetAttribute("value")); } + [Fact] + public void Should_carry_the_antiforgery_token_the_request_generates_when_rendered_statically() + { + // Arrange + using var ctx = new FormaThemePickerTests(); + ctx.Services.AddSingleton(CreateTokenProvider()); + ctx.SetRendererInfo(new RendererInfo("Static", isInteractive: false)); + + // Act + var cut = ctx.Render(@); + + // Assert + Assert.Equal("request-token", cut.Find("form.forma-theme-picker input[type=hidden][name=__RequestVerificationToken]").GetAttribute("value")); + } + + [Fact] + public void Should_carry_no_antiforgery_token_where_the_request_generates_none() + { + // Arrange + using var ctx = new FormaThemePickerTests(); + ctx.Services.AddSingleton(new FakeAntiforgeryStateProvider(null)); + ctx.SetRendererInfo(new RendererInfo("Static", isInteractive: false)); + + // Act + var cut = ctx.Render(@); + + // Assert + Assert.Multiple( + () => Assert.Equal("/", cut.Find("form.forma-theme-picker input[name=returnUrl]").GetAttribute("value")), + () => Assert.Empty(cut.FindAll("input[name=__RequestVerificationToken]"))); + } + + [Fact] + public void Should_carry_no_antiforgery_token_when_interactive() + { + // Arrange + using var ctx = new FormaThemePickerTests(); + ctx.Services.AddSingleton(CreateTokenProvider()); + + // Act + var cut = ctx.Render(@); + + // Assert + Assert.Empty(cut.FindAll("input[name=__RequestVerificationToken]")); + } + [Fact] public void Should_leave_the_theme_list_out_where_the_host_registered_one_theme() { @@ -185,6 +241,38 @@ }); } + [Fact] + public void Should_carry_the_antiforgery_token_the_request_generates_in_each_form_when_rendered_statically() + { + // Arrange + using var ctx = new FormaThemePickerTests(); + ctx.Services.AddSingleton(CreateTokenProvider()); + ctx.SetRendererInfo(new RendererInfo("Static", isInteractive: false)); + + // Act + var cut = ctx.Render(@); + + // Assert + Assert.Equal(["request-token", "request-token"], cut.FindAll("form").Select(form => form.QuerySelector("input[type=hidden][name=__RequestVerificationToken]")?.GetAttribute("value"))); + } + + [Fact] + public void Should_carry_no_antiforgery_token_in_either_form_where_the_request_generates_none() + { + // Arrange + using var ctx = new FormaThemePickerTests(); + ctx.Services.AddSingleton(new FakeAntiforgeryStateProvider(null)); + ctx.SetRendererInfo(new RendererInfo("Static", isInteractive: false)); + + // Act + var cut = ctx.Render(@); + + // Assert + Assert.Multiple( + () => Assert.Equal(2, cut.FindAll("form[method=post][action='_forma/themes']").Count), + () => Assert.Empty(cut.FindAll("input[name=__RequestVerificationToken]"))); + } + [Fact] public void Should_mark_the_choice_in_force_pressed() { diff --git a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewPageCheck.razor b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewPageCheck.razor new file mode 100644 index 000000000..179fb7c59 --- /dev/null +++ b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewPageCheck.razor @@ -0,0 +1,17 @@ +@page "/{Runtime}/data-view-page" +@using Forma.Blazor.Components.DataView + +@* Sixty rows in a grid no ancestor bounds, so the view takes the height of its rows and the page scrolls them. *@ + + + + + + + + +@code { + private static readonly IQueryable Rows = Enumerable.Range(1, 60).Select(index => new Row($"Row {index}")).ToArray().AsQueryable(); + + internal sealed record Row(string Name); +} diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/ComponentChecks.cs b/tests/e2e/Forma.Blazor.Browser.Tests/ComponentChecks.cs index 99f006015..55bd9e271 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/ComponentChecks.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/ComponentChecks.cs @@ -290,24 +290,30 @@ public static async Task WaitForObservationAsync(IPage page, string selector, st /// The page read. /// The data view's selector. /// A task that completes once the region is no longer busy. - /// It waits as long as a wait for a script's first answer does. - public static Task WaitForDataViewAsync(IPage page, string selector) + /// + /// It waits as long as a wait for a script's first answer does, reading the region in the page, since an assertion that finds + /// it still busy describes the whole view, hundreds of items on some pages, and holds the page from drawing the answer it waits for. + /// + public static async Task WaitForDataViewAsync(IPage page, string selector) { ArgumentNullException.ThrowIfNull(page); - return Assertions.Expect(page.Locator(selector).Locator(".forma-data-view-region").First).Not.ToHaveAttributeAsync("aria-busy", "true", new() { Timeout = 30000 }); + await page.WaitForFunctionAsync("selector => { const region = document.querySelector(selector)?.querySelector('.forma-data-view-region'); return region != null && region.getAttribute('aria-busy') !== 'true'; }", selector, new() { Timeout = 30000 }).ConfigureAwait(false); } /// Waits until the first node of the tree names is enabled, which its nodes are once the tree's keys and its data view's script have attached. /// The page read. /// The tree's selector. /// A task that completes once the tree's first node is enabled. - /// It waits as long as a wait for a script's first answer does. - public static Task WaitForTreeAsync(IPage page, string selector) + /// + /// It waits as long as a wait for a script's first answer does, reading the node in the page, as + /// reads its region, a node disabled by itself or by any element holding it. + /// + public static async Task WaitForTreeAsync(IPage page, string selector) { ArgumentNullException.ThrowIfNull(page); - return Assertions.Expect(page.Locator(selector).GetByRole(AriaRole.Treeitem).First).ToBeEnabledAsync(new() { Timeout = 30000 }); + await page.WaitForFunctionAsync("selector => { const node = document.querySelector(selector)?.querySelector('[role=treeitem]'); return node != null && node.closest('[aria-disabled=true]') === null; }", selector, new() { Timeout = 30000 }).ConfigureAwait(false); } /// Waits until the rich text canvas inside the element names is enabled, which it is once its edits have attached. diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs index eaca041b3..d145ab915 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs @@ -704,6 +704,26 @@ public async Task Should_keep_the_current_folder_the_open_folders_the_selection_ } } + public sealed class DataViewPage(BrowserHost host) + { + [Theory] + [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_let_the_wheel_over_its_rows_scroll_the_page_it_grows_with(string runtime) + { + // Arrange — the pointer over a row of a view as tall as its rows + var (context, page) = await OpenAsync(host, runtime, "data-view-page"); + await using var _ = context; + await WaitForDataViewAsync(page, "#check"); + await page.Locator("#check tbody tr").Nth(2).HoverAsync(); + + // Act + await page.Mouse.WheelAsync(0, 300); + + // Assert + await page.WaitForFunctionAsync("() => window.scrollY > 0"); + } + } + public sealed class DataViewTabOrder(BrowserHost host) { [Theory] diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/ExplorerTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/ExplorerTests.cs index ce676388f..de83fbf0e 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/ExplorerTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/ExplorerTests.cs @@ -573,5 +573,23 @@ await page.WaitForFunctionAsync( () => Assert.True(overHeader.Length == 0, $"Standing over the header's bottom edge: {string.Join(", ", overHeader)}")); await Assertions.Expect(page.Locator("#check .forma-data-card-name")).ToHaveCountAsync(200); } + + [Theory] + [MemberData(nameof(ComponentChecks.Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_let_the_wheel_over_its_items_scroll_the_page_on_a_phone(string runtime) + { + // Arrange — the pointer over an item of the explorer flowing in a phone's page + var (context, page) = await ComponentChecks.OpenAsync(host, runtime, "explorer-page"); + await using var _ = context; + await page.SetViewportSizeAsync(360, 640); + await ComponentChecks.WaitForDataViewAsync(page, "#check"); + await page.Locator("#check .forma-data-card-name").First.HoverAsync(); + + // Act + await page.Mouse.WheelAsync(0, 300); + + // Assert + await page.WaitForFunctionAsync("() => window.scrollY > 0"); + } } } diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs index ee8cb03fd..c1127f060 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs @@ -24,10 +24,52 @@ public sealed class TransferTests private static string Describe(string value) => $"{value.Length}:{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))[..16]}"; + // Each field of the page's two forms, how many characters the browser holds in it and whether its edits listen, and how many saves ran. + private const string DescribeFields = """ + async () => { + window.formaDomEngine ??= await import(new URL('_content/forma/browser/scripts/DomEngine.js', document.baseURI).href); + const fields = ['#forma-notes', '#forma-code', '#forma-body .forma-composer-rich-text-canvas', '#host-name', '#host-notes'].map(selector => { + const field = document.querySelector(selector); + if (!field) { + return `${selector} isn't drawn`; + } + + const length = 'value' in field ? field.value.length : field.innerHTML.length; + const listens = window.formaDomEngine.describe(field).capabilities.includes('edits'); + return `${selector} holds ${length} characters, its edits ${listens ? 'listening' : 'not listening'}`; + }); + return [...fields, `${document.getElementById('saves')?.textContent} saves ran`].join('; '); + } + """; + // The document of two megabytes, every word of it the one given. private static string CreateDocument(string word) => string.Concat(Enumerable.Repeat($"

{string.Join(' ', Enumerable.Repeat(word, ParagraphWords))}

", Paragraphs)); + // Waits for what a save leaves on the page, failing with what each field holds in the browser and whether its edits listen. + private static async Task ExpectSavedAsync(IPage page, Func expectation) + { + try + { + await expectation(); + } + catch (PlaywrightException exception) + { + string fields; + + try + { + fields = await page.EvaluateAsync(DescribeFields).WaitAsync(TimeSpan.FromSeconds(5)); + } + catch (TimeoutException) + { + fields = "the page didn't answer a script within five seconds, its main thread held"; + } + + Assert.Fail($"{exception.Message}{Environment.NewLine}The forms' fields: {fields}"); + } + } + public sealed class Forms(BrowserHost host) { [Theory] @@ -46,7 +88,7 @@ public async Task Should_save_a_text_of_megabytes_through_a_form_of_forma_own(st await page.Locator("#forma-save").ClickAsync(); // Assert - await Assertions.Expect(page.Locator("#forma-notes-saved")).ToHaveTextAsync(Describe(notes), Reached); + await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-notes-saved")).ToHaveTextAsync(Describe(notes), Reached)); await Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1"); } @@ -65,7 +107,7 @@ public async Task Should_save_the_last_word_typed_into_the_rich_text_editor_insi await page.Locator("#forma-save").ClickAsync(); // Assert - await Assertions.Expect(page.Locator("#forma-body-end")).ToContainTextAsync("Hello world"); + await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-body-end")).ToContainTextAsync("Hello world")); } [Theory] @@ -84,7 +126,7 @@ public async Task Should_save_a_document_of_megabytes_pasted_into_the_rich_text_ await page.Locator("#forma-save").ClickAsync(); // Assert - await Assertions.Expect(page.Locator("#forma-body-saved")).ToHaveTextAsync(Describe(document), Reached); + await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-body-saved")).ToHaveTextAsync(Describe(document), Reached)); } [Theory] @@ -105,7 +147,7 @@ public async Task Should_submit_a_text_of_megabytes_with_enter_through_a_form_of await page.Locator("#host-name").PressAsync("Enter"); // Assert - await Assertions.Expect(page.Locator("#host-saved")).ToHaveTextAsync($"Ada {Describe(notes)}", Reached); + await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#host-saved")).ToHaveTextAsync($"Ada {Describe(notes)}", Reached)); await Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1"); } @@ -133,7 +175,7 @@ public async Task Should_run_no_save_while_a_text_did_not_arrive_and_save_once_i await page.Locator("#forma-save").ClickAsync(); // Assert - await Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1"); + await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1")); } } diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/ScriptHold.cs b/tests/e2e/Forma.Blazor.Browser.Tests/ScriptHold.cs index b5908636d..7d7ccef68 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/ScriptHold.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/ScriptHold.cs @@ -1,11 +1,12 @@ namespace Forma.Blazor.Browser.Tests; using System.Collections.Concurrent; +using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; /// The hold an early run keeps on a page's Forma scripts: each one the page requests once its runtime starts connecting waits until half a second after the page takes its first press, key or input, or two seconds after the page becomes interactive where it takes none. -/// Blazor starts only once Forma's JavaScript initializers and what they import have loaded, the Server's before its circuit connects and WebAssembly's as its runtime loads, so an initializer passes, and so does each script it imports, directly or through the scripts it imports, read from each one's text as it passes. What's held is what a component imports as it attaches, the input router's, the DOM watcher's and engine's and its own. The page reports its first input from the capture phase of the window's listeners, ahead of any of its own. Once released, the page's scripts go unrouted, so the modules they import load as in a plain run. +/// Blazor starts only once Forma's JavaScript initializers and what they import have loaded, the Server's before its circuit connects and WebAssembly's as its runtime loads, so an initializer passes, and so does each script it imports, directly or through the scripts it imports, read from each one's text as it passes. What's held is what a component imports as it attaches, the input router's, the DOM watcher's and engine's and its own. The page reports its first input from the capture phase of the window's listeners, ahead of any of its own. Once released, each script held goes on and then the page's scripts go unrouted, so the modules they import load as in a plain run. As the page closes, the hold writes to the check's output when it took the page's first input, when it released the scripts and which were still loading. public sealed partial class ScriptHold { // Reports the page's first press, key or input to the hold, ahead of every listener of the page's own. @@ -26,8 +27,13 @@ public sealed partial class ScriptHold private readonly IPage _page; private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly ConcurrentDictionary _startScripts = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _routings = new(); + private readonly ConcurrentDictionary _loadingScripts = new(); + private readonly Stopwatch _clock = Stopwatch.StartNew(); private int _isConnecting; private int _hasTakenInput; + private long _firstInputAt = -1; + private long _releasedAt = -1; private ScriptHold(IPage page) { @@ -62,6 +68,7 @@ public static async Task InstallAsync(IPage page) ArgumentNullException.ThrowIfNull(page); var hold = new ScriptHold(page); + var output = TestContext.Current.TestOutputHelper; Holds.Add(page, hold); page.Request += (_, request) => { @@ -69,10 +76,18 @@ public static async Task InstallAsync(IPage page) { Interlocked.Exchange(ref hold._isConnecting, 1); } + + if (FormaScript().IsMatch(request.Url)) + { + hold._loadingScripts[request] = hold._clock.ElapsedMilliseconds; + } }; + page.RequestFinished += (_, request) => hold._loadingScripts.TryRemove(request, out long _); + page.RequestFailed += (_, request) => hold._loadingScripts.TryRemove(request, out long _); + page.Close += (_, _) => hold.Report(output); await page.ExposeFunctionAsync("formaTookInput", hold.TakeInput).ConfigureAwait(false); await page.AddInitScriptAsync(ReportFirstInput).ConfigureAwait(false); - await page.RouteAsync(FormaScript(), hold.RouteAsync).ConfigureAwait(false); + await page.RouteAsync(FormaScript(), hold.RouteTrackedAsync).ConfigureAwait(false); return hold; } @@ -89,6 +104,22 @@ private static bool IsRuntimeConnecting(string address) private static string GetScriptAddress(string address) => Fingerprint().Replace(new Uri(address).GetLeftPart(UriPartial.Path), string.Empty); + // A script's routing is kept until it ends, so the release lets every script held go on before the route goes. + private async Task RouteTrackedAsync(IRoute route) + { + var routing = RouteAsync(route); + _routings.TryAdd(routing, true); + + try + { + await routing.ConfigureAwait(false); + } + finally + { + _routings.TryRemove(routing, out _); + } + } + // A script an initializer imports, directly or through another, passes, read for the scripts it imports in turn; any other waits // while the hold holds it. private async Task RouteAsync(IRoute route) @@ -122,6 +153,7 @@ private void TakeInput() { if (Interlocked.Exchange(ref _hasTakenInput, 1) == 0) { + Interlocked.Exchange(ref _firstInputAt, _clock.ElapsedMilliseconds); _ = ReleaseAfterAsync(InputGrace); } } @@ -142,7 +174,8 @@ private async Task ReleaseAfterAsync(TimeSpan delay) await ReleaseAsync().ConfigureAwait(false); } - // The scripts held go on, and every script requested after them goes unrouted, the page closing meanwhile ending nothing. + // The scripts held go on, and once each has, every script requested after them goes unrouted, the page closing meanwhile ending + // nothing; a route taken away while a script held still waits on it would leave that script unanswered. private async Task ReleaseAsync() { if (!_released.TrySetResult()) @@ -150,6 +183,9 @@ private async Task ReleaseAsync() return; } + Interlocked.Exchange(ref _releasedAt, _clock.ElapsedMilliseconds); + await Task.WhenAll(_routings.Keys).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing); + try { await _page.UnrouteAsync(FormaScript()).ConfigureAwait(false); @@ -159,6 +195,24 @@ private async Task ReleaseAsync() } } + // When the hold took the page's first input and released its scripts, and which of them were still loading, since the page opened. + private void Report(ITestOutputHelper? output) + { + var firstInputAt = Interlocked.Read(ref _firstInputAt); + var releasedAt = Interlocked.Read(ref _releasedAt); + var loading = _loadingScripts.OrderBy(script => script.Value).Select(script => $"{new Uri(script.Key.Url).Segments[^1]} from {script.Value} ms").ToList(); + var report = $"The hold took the page's first input {(firstInputAt < 0 ? "at no time" : $"at {firstInputAt} ms")} and released its scripts {(releasedAt < 0 ? "at no time" : $"at {releasedAt} ms")}; as the page closed {(loading.Count == 0 ? "no Forma script was still loading" : $"these were still loading: {string.Join(", ", loading)}")}."; + + try + { + output?.WriteLine(report); + } + catch (InvalidOperationException) + { + // The check has ended, and its output with it. + } + } + // A script of Forma's, served under _content/forma/ or under its assembly's name, which the browser matches without asking the // check, so every other request the page makes goes on unrouted. [GeneratedRegex(@"/_content/(?:forma/|Forma\.)[^?#]*\.m?js(?:[?#]|$)")] diff --git a/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Forma.Framework.Themes.Blazor.Server.Integration.Tests.csproj b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Forma.Framework.Themes.Blazor.Server.Integration.Tests.csproj new file mode 100644 index 000000000..e8aef37ac --- /dev/null +++ b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Forma.Framework.Themes.Blazor.Server.Integration.Tests.csproj @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Support/ThemeSwitchHost.cs b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Support/ThemeSwitchHost.cs new file mode 100644 index 000000000..bdda0263e --- /dev/null +++ b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/Support/ThemeSwitchHost.cs @@ -0,0 +1,67 @@ +namespace Forma.Framework.Themes.Blazor.Server.Integration.Tests.Support; + +using Forma.Framework.Localization; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +/// An application built as a host builds one, taking theme switches on a loopback port, which validates antiforgery tokens where it is set to. +internal sealed class ThemeSwitchHost(WebApplication application) : IAsyncDisposable +{ + /// Starts an application registering Forma's theme and Harbor, which calls UseAntiforgery() where . + public static async Task StartAsync(bool validatesTokens) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Services.AddFormaThemeServerIntegration(); + builder.Services.AddFormaThemes(themes => + { + themes.Add(Define("forma")); + themes.Add(Define("harbor")); + }); + + if (validatesTokens) + { + builder.Services.AddAntiforgery(); + } + + var application = builder.Build(); + application.UseFormaThemes(); + + if (validatesTokens) + { + application.UseAntiforgery(); + } + + application.MapFormaThemes(); + await application.StartAsync().ConfigureAwait(false); + + return new ThemeSwitchHost(application); + } + + /// Posts a switch to Harbor in its dark scheme, carrying no antiforgery token, from where says a browser sent it. + public async Task PostSwitchAsync(string site) + { + using var handler = new HttpClientHandler { AllowAutoRedirect = false, CheckCertificateRevocationList = true }; + using var client = new HttpClient(handler) { BaseAddress = new Uri(application.Urls.Single()) }; + using var request = new HttpRequestMessage(HttpMethod.Post, ThemeApplicationBuilderExtensions.SwitchPath) + { + Content = new FormUrlEncodedContent([new("theme", "harbor"), new("scheme", "dark"), new("returnUrl", "/settings")]), + }; + request.Headers.Add("Sec-Fetch-Site", site); + + return await client.SendAsync(request).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + await application.StopAsync().ConfigureAwait(false); + await application.DisposeAsync().ConfigureAwait(false); + } + + private static ThemeDefinition Define(string name) + => new(name, LocalizableText.For(name), ColorSchemes.Light | ColorSchemes.Dark, $"css/{name}.css"); +} diff --git a/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/ThemeSwitchEndpointTests.cs b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/ThemeSwitchEndpointTests.cs new file mode 100644 index 000000000..3442f381c --- /dev/null +++ b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/ThemeSwitchEndpointTests.cs @@ -0,0 +1,62 @@ +namespace Forma.Framework.Themes.Blazor.Server.Integration.Tests; + +using System.Net; + +using Forma.Framework.Themes.Blazor.Server.Integration.Tests.Support; + +public sealed class ThemeSwitchEndpointTests +{ + public sealed class FetchMetadata + { + [Fact] + public async Task Should_take_a_switch_without_a_token_from_the_application_s_own_page() + { + // Arrange + await using var host = await ThemeSwitchHost.StartAsync(validatesTokens: false); + + // Act + using var response = await host.PostSwitchAsync("same-origin"); + + // Assert + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.Found, response.StatusCode), + () => Assert.Equal("/settings", response.Headers.Location?.OriginalString), + () => Assert.StartsWith("forma-theme=theme%3Dharbor%26scheme%3Ddark", Assert.Single(response.Headers.GetValues("Set-Cookie")), StringComparison.Ordinal)); + } + + [Theory] + [InlineData("same-site")] + [InlineData("cross-site")] + public async Task Should_refuse_a_switch_another_site_posts(string site) + { + // Arrange + await using var host = await ThemeSwitchHost.StartAsync(validatesTokens: false); + + // Act + using var response = await host.PostSwitchAsync(site); + + // Assert + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.Headers.Contains("Set-Cookie"))); + } + } + + public sealed class AntiforgeryTokens + { + [Fact] + public async Task Should_refuse_a_switch_without_a_token_from_the_application_s_own_page() + { + // Arrange + await using var host = await ThemeSwitchHost.StartAsync(validatesTokens: true); + + // Act + using var response = await host.PostSwitchAsync("same-origin"); + + // Assert + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.Headers.Contains("Set-Cookie"))); + } + } +} diff --git a/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/_Imports.cs b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/_Imports.cs new file mode 100644 index 000000000..c802f4480 --- /dev/null +++ b/tests/integration/Framework/Forma.Framework.Themes.Blazor.Server.Integration.Tests/_Imports.cs @@ -0,0 +1 @@ +global using Xunit; diff --git a/tests/scripts/package-lock.json b/tests/scripts/package-lock.json index 033c4cb51..94208c8e5 100644 --- a/tests/scripts/package-lock.json +++ b/tests/scripts/package-lock.json @@ -1205,9 +1205,9 @@ } }, "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", + "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", "dev": true, "license": "MIT", "engines": {