From d21ca2d9da2489118ca1318a74d79fa49069e20b Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:56:27 +0200 Subject: [PATCH 01/10] chore: declare 1.0.0-preview.26 --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 30ac97ed..1765ecc4 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -27,7 +27,7 @@ 1.0.0 - preview.25 + preview.26 From 43175487f84219c9f668fcf2f7fdb827ae8df181 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:06:43 +0200 Subject: [PATCH 02/10] fix(field): rest a field's label centered on its box, and over a text area level with a one-line field's --- CHANGELOG.md | 8 ++++ .../Components/FormaField.razor.css | 19 +++------ .../FieldLabelCheck.razor | 11 ++++- .../Components/RootTests.cs | 40 +++++++++++++++++++ 4 files changed, 64 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62a950c5..ce952de6 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.26` + +*Unreleased* + +- A [labeled field](docs/component-catalog.md#formafield)'s resting label stands centered on its box again, and over + a `FormaTextArea` level with where a one-line field's rests, where it sat on the value's line at the box's lower edge + and over the text area's first line. + ## `1.0.0-preview.25` *December 2, 2026* diff --git a/src/Blazor/Forma.Blazor/Components/FormaField.razor.css b/src/Blazor/Forma.Blazor/Components/FormaField.razor.css index 0e1287b0..025a56e3 100644 --- a/src/Blazor/Forma.Blazor/Components/FormaField.razor.css +++ b/src/Blazor/Forma.Blazor/Components/FormaField.razor.css @@ -182,10 +182,9 @@ } } -/* Floating and Pinned: the label lies over the whole box and either rests over the value's row, its last line where the - value's line stands and the lines before it wrapping up into the room above, or floats into that room, lying exactly - over its copy. The room either side of its text moves it between the two, and a resting label too tall for the box - runs out at its top, never past its end. It lies beneath the element and what stands over it, which its text shows +/* Floating and Pinned: the label lies over the whole box and either rests centered on it, or floats into the room above + the value, lying exactly over its copy. The room either side of its text moves it between the two, and a resting label + too tall for the box runs out at its top, never past its end. It lies beneath the element and what stands over it, which its text shows through, so a press the element or a button doesn't take, in the room above the value among it, is the label's, and reaches the element as a label's does. */ .forma-field-box-floating-label { @@ -199,8 +198,7 @@ display: flex; flex-direction: column; justify-content: flex-end; - /* A resting line centered on the value's row, which ends the box, and clear of a button at its end. */ - padding-block-end: calc((var(--forma-field-value-block-size) - 1lh) / 2); + /* A resting label clear of a button at the value's end. */ padding-inline-end: var(--forma-field-label-end-room); font-size: var(--font-size-sm); font-weight: inherit; @@ -229,17 +227,12 @@ transition: flex-grow 0.1s ease-in-out; } -.forma-field-box-floating-label > .forma-field-label::after { - flex-grow: 0; -} - .forma-field-box-floating-label > .forma-field-label > .forma-field-label-text { - padding-block-start: var(--forma-field-label-offset); padding-inline: var(--space-3); transition: padding-block-start 0.1s ease-in-out; } -/* An element taller than one line holds the resting label over its first line, a step beneath the label's room. */ +/* An element taller than one line holds the resting label centered on the field's step, where a one-line field's rests. */ .forma-field-multiline > .forma-field-box-floating-label > .forma-field-label::before { flex-grow: 0; } @@ -249,7 +242,7 @@ } .forma-field-multiline > .forma-field-box-floating-label > .forma-field-label > .forma-field-label-text { - padding-block-start: calc(var(--forma-field-label-room-block-size) + var(--space-1) + (var(--font-size-sm) * var(--line-height-prose) - 1lh) / 2); + padding-block-start: calc((var(--forma-field-label-room-block-size) + var(--forma-field-value-block-size) - 1lh) / 2); } /* Floated: the element focused, holding a value (its placeholder not shown, or has-value), or the label pinned. */ diff --git a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/FieldLabelCheck.razor b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/FieldLabelCheck.razor index d1d72b88..4bac6e74 100644 --- a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/FieldLabelCheck.razor +++ b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/FieldLabelCheck.razor @@ -1,7 +1,8 @@ @page "/{Runtime}/field-label" @* A number input in each direction, each labeled at more length than a phone's width holds on one line, its label resting - until the input takes the focus, and a password box in each direction labeled in one line, its toggle at the value's end. *@ + until the input takes the focus, a password box in each direction labeled in one line, its toggle at the value's end, and + a text box and a text area labeled in one line. *@
@@ -14,10 +15,18 @@
+
+ +
+
+ +
@code { private decimal? _ltrPrice; private decimal? _rtlPrice; private string? _ltrPassword; private string? _rtlPassword; + private string? _title; + private string? _notes; } diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/RootTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/RootTests.cs index 5a418d86..ca4489ae 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/RootTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/RootTests.cs @@ -41,6 +41,22 @@ public sealed class RootTests private const string ReadBoxHeight = "id => document.getElementById(id).closest('.forma-field-box').getBoundingClientRect().height"; + // How far the resting label's text of the field around the input id names stands from where it rests: centered on the box, + // or, over an element taller than one line, centered on the field's step, where a one-line field's label rests. + private const string ReadRestingLabelOffset = """ + id => { + const box = document.getElementById(id).closest('.forma-field-box'); + const range = document.createRange(); + range.selectNodeContents(box.querySelector(':scope > .forma-field-label .forma-field-label-text')); + const text = range.getBoundingClientRect(); + const bounds = box.getBoundingClientRect(); + const rem = parseFloat(getComputedStyle(document.documentElement).fontSize); + const step = parseFloat(getComputedStyle(box).getPropertyValue('--target-size-xl')) * rem; + const center = box.closest('.forma-field-multiline') ? bounds.top + step / 2 : bounds.top + bounds.height / 2; + return (text.top + text.bottom) / 2 - center; + } + """; + // What keeps the password box id names from standing at the field's step with its toggle at the value's end: its box's height, // its toggle's target smaller than a target takes under the page's pointer, a finger's where the pointer is coarse, or a line of // its label over that target. @@ -102,6 +118,30 @@ public async Task Should_show_a_long_label_whole_at_a_phone_s_width_and_keep_its () => Assert.Equal(restingHeights["rtl"], floatedHeights["rtl"], 0.5)); } + [Theory] + [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_rest_its_label_centered_on_its_box_or_over_a_taller_element_on_the_field_s_step(string runtime) + { + // Arrange — every field resting: a label on one line and on several, a toggle at the value's end, and a text area + var (context, page) = await OpenAsync(host, runtime, "field-label"); + await using var _ = context; + var offsets = new List(); + + // Act + foreach (var id in (string[])["ltr", "rtl", "ltr-password", "rtl-password", "title", "notes"]) + { + var offset = await page.EvaluateAsync(ReadRestingLabelOffset, id); + + if (Math.Abs(offset) > 1) + { + offsets.Add($"{id}'s resting label stands {offset:0.0}px off its center"); + } + } + + // Assert + Assert.Empty(offsets); + } + [Theory] [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] public async Task Should_stand_at_its_step_with_a_button_at_its_value_s_end_its_label_clear_of_the_button_under_any_pointer(string runtime) From 4b32344d8669373cbaf086e056286b2475a5fd02 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:03:32 +0200 Subject: [PATCH 03/10] fix(sortable-list): give a press on a nested list's handle to that list alone --- CHANGELOG.md | 2 ++ docs/features-status.md | 5 +++-- .../scripts/behaviors/ReorderInteraction.js | 6 ++++-- .../Collections/SortableListCheck.razor | 18 +++++++++++++++- .../Components/CollectionsTests.cs | 20 ++++++++++++++++++ .../behaviors/ReorderInteraction.test.js | 21 +++++++++++++++++++ 6 files changed, 67 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce952de6..05a67d84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ set out. What Forma gained before its first release, month by month, is in [the - A [labeled field](docs/component-catalog.md#formafield)'s resting label stands centered on its box again, and over a `FormaTextArea` level with where a one-line field's rests, where it sat on the value's line at the box's lower edge and over the text area's first line. +- A `FormaSortableList` nested in another's item takes a press and a drag of its own handles, by mouse, pen or touch, + as it takes their keys, where the press lifted the item of the list around it and the nested list kept its order. ## `1.0.0-preview.25` diff --git a/docs/features-status.md b/docs/features-status.md index ad47ae94..48d9de18 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -27,7 +27,7 @@ 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, thirty-one changes fixed, and one already met | +| [A host's requests](#a-hosts-requests) | Four components implemented and one on the roadmap, thirty-two 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 | @@ -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-two changes to components that exist, listed here in the order they are taken, +`FormaCommandPalette` is, and thirty-three 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 | @@ -259,6 +259,7 @@ each with what the code does and its state. | 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 | +| A sortable list in another's item | Every `FormaSortableList` on the path of a press on a handle took it, so a press on the handle of a list nested in another's item lifted the outer list's item, and the inner list kept its order. The press is a route on the input router, as the handle's keys are, so the innermost list whose handle it is takes it alone | Fixed | diff --git a/src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/behaviors/ReorderInteraction.js b/src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/behaviors/ReorderInteraction.js index 1926ac61..aa4ac468 100644 --- a/src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/behaviors/ReorderInteraction.js +++ b/src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/behaviors/ReorderInteraction.js @@ -2,8 +2,9 @@ * ReorderInteraction — dragging or keying an item into a new position in its list * * Built on DragGesture: a pointer drag finds the item under the pointer and the side of it - * the dragged item lands on, and the keys on a handle are routes on the input router. The - * owner is told the resulting position once per completed move. + * the dragged item lands on. The press that starts a drag and the keys on a handle are + * routes on the input router, so a list nested in another's item takes its own handles' + * presses and keys. The owner is told the resulting position once per completed move. */ import { attach as attachDragGesture } from './DragGesture.js'; @@ -79,6 +80,7 @@ class ReorderInteraction { this.#afterClass = afterClass; this.#gesture = attachDragGesture(list, { + action: 'sortable-list.drag', // A handle carries touch-action: none, so only whole-item dragging needs the hold. holdDelay: dragFromItem ? TouchHold : 0, findSubject: event => this.#findSubject(event), diff --git a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/Collections/SortableListCheck.razor b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/Collections/SortableListCheck.razor index 570f607f..3ccb4dc7 100644 --- a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/Collections/SortableListCheck.razor +++ b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/Collections/SortableListCheck.razor @@ -1,6 +1,7 @@ @page "/{Runtime}/sortable-list" -@* Three items reordered by their handles, and three more dragged by their rows, each in the order the check reads. *@ +@* Three items reordered by their handles, three more dragged by their rows, and two sections whose first holds a list of + its own in its item, each list in the order the check reads. *@ @item @@ -9,8 +10,23 @@ @item @string.Join(", ", _rows) + + + @section + @if (section == "Fruit") + { + + @fruit + + } + + +@string.Join(", ", _sections) +@string.Join(", ", _fruit) @code { private IReadOnlyList _items = ["Alpha", "Beta", "Gamma"]; private IReadOnlyList _rows = ["Red", "Green", "Blue"]; + private IReadOnlyList _sections = ["Fruit", "Vegetables"]; + private IReadOnlyList _fruit = ["Apple", "Pear"]; } diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/CollectionsTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/CollectionsTests.cs index 64e588fc..f3e3645f 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/CollectionsTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/CollectionsTests.cs @@ -67,6 +67,26 @@ public async Task Should_move_a_row_dragged_by_its_content_where_its_rows_are_dr await Assertions.Expect(page.Locator("#rows-result")).ToHaveTextAsync("Green, Red, Blue"); } + [Theory] + [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_move_only_a_nested_list_s_item_by_a_drag_of_its_handle(string runtime) + { + // Arrange — a list nested in the first section's item + var (context, page) = await OpenAsync(host, runtime, "sortable-list"); + await using var _ = context; + SkipGestureInEarlyRun(page); + await WaitForInputScopeAsync(page, "#sections"); + await WaitForInputScopeAsync(page, "#fruit"); + var fruit = page.Locator("#fruit .forma-sortable-list-item"); + + // Act + await DragAsync(page, page.Locator("#fruit .forma-sortable-list-handle").First, fruit.Nth(1)); + + // Assert + await Assertions.Expect(page.Locator("#fruit-result")).ToHaveTextAsync("Pear, Apple"); + await Assertions.Expect(page.Locator("#sections-result")).ToHaveTextAsync("Fruit, Vegetables"); + } + // A drag from the middle of what is held to the lower half of the item it lands after. private static async Task DragAsync(IPage page, ILocator held, ILocator target) { diff --git a/tests/scripts/browser/behaviors/ReorderInteraction.test.js b/tests/scripts/browser/behaviors/ReorderInteraction.test.js index 858094c6..8187513e 100644 --- a/tests/scripts/browser/behaviors/ReorderInteraction.test.js +++ b/tests/scripts/browser/behaviors/ReorderInteraction.test.js @@ -296,6 +296,27 @@ describe('ReorderInteraction', () => { reordered().not.toHaveBeenCalled(); }); + it('drags a nested list\'s item alone when its handle is pressed', () => { + labelOf(0).insertAdjacentHTML('afterend', `
    ${row('Inner one')}${row('Inner two')}
`); + const inner = document.querySelector('#inner'); + const innerItems = [...inner.querySelectorAll(':scope > .forma-sortable-list-item')]; + const innerOwner = fakeOwner(); + stubPointerCapture(inner); + stackRows(innerItems); + attachList({ owner }); + handles.push(attach(inner, { owner: innerOwner })); + + press(innerItems[0].querySelector('.forma-sortable-list-handle'), rowOf(0).middle); + inner.dispatchEvent(pointerEvent('pointermove', { clientY: rowOf(1).middle + 10 })); + const isOuterDragging = list.classList.contains(ACTIVE) || items().some(item => item.parentElement === list && item.classList.contains(DRAGGING)); + const isInnerDragging = inner.classList.contains(ACTIVE) && innerItems[0].classList.contains(DRAGGING); + inner.dispatchEvent(pointerEvent('pointerup', { clientY: rowOf(1).middle + 10 })); + + expect({ isOuterDragging, isInnerDragging }).toEqual({ isOuterDragging: false, isInnerDragging: true }); + expect(innerOwner.invokeMethodAsync).toHaveBeenCalledExactlyOnceWith('HandleReorderAsync', 0, 1, true); + reordered().not.toHaveBeenCalled(); + }); + it('clears every mark once the item lands', () => { attachList({ owner }); From 1e2b19ee47de471d5dfc54d99fb088aa76677892 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:21:02 +0200 Subject: [PATCH 04/10] feat(data-view): give the focus to the item a key names once the items on their way have arrived --- CHANGELOG.md | 3 + docs/data-view-design.md | 9 ++ docs/features-status.md | 5 +- .../FormaDataView.razor.cs | 80 ++++++++++++++++ .../Interop/DataViewJsonContext.cs | 9 ++ .../Interop/SelectionInteraction.cs | 6 ++ .../Forma.Blazor.DataView/ItemTokenTable.cs | 21 +++++ src/Blazor/Forma.Blazor.DataView/README.md | 23 +++++ .../wwwroot/scripts/SelectionInteraction.js | 60 +++++++++--- .../Components/FormaDataViewTests.razor | 92 +++++++++++++++++++ .../DataView/DataViewReturnCheck.razor | 59 ++++++++++++ .../Components/DataViewTests.cs | 46 ++++++++++ .../dataview/SelectionInteraction.test.js | 74 +++++++++++++++ 13 files changed, 470 insertions(+), 17 deletions(-) create mode 100644 src/Blazor/Forma.Blazor.DataView/Interop/DataViewJsonContext.cs create mode 100644 tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewReturnCheck.razor diff --git a/CHANGELOG.md b/CHANGELOG.md index 05a67d84..cf138a4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ set out. What Forma gained before its first release, month by month, is in [the and over the text area's first line. - A `FormaSortableList` nested in another's item takes a press and a drag of its own handles, by mouse, pen or touch, as it takes their keys, where the press lifted the item of the list around it and the nested list kept its order. +- `FormaDataView` takes `FocusItemAsync`, which brings the item a key names back on screen with the focus once the + items on their way have arrived, so a reader coming back to a list lands on the item they opened, as + [the data view design](docs/data-view-design.md#virtualization-and-the-scroll-region) sets out. ## `1.0.0-preview.25` diff --git a/docs/data-view-design.md b/docs/data-view-design.md index 90e4fff9..8cc04025 100644 --- a/docs/data-view-design.md +++ b/docs/data-view-design.md @@ -391,6 +391,15 @@ items on screen stay put, `InitialItemIndex` opens the data view on an item, and `ScrollToItemAsync` scrolls to one later, and moves a paged data view to the item's page. The region announces its real item count, so assistive technology knows how many items exist rather than how many are drawn. +`FocusItemAsync` gives the focus to the item a key names, as a host bringing a reader back to +the item they opened does. It waits for the items on their way, a page loading or one +appending, and for the behavior that lands the focus to attach. It then looks for the item +on the page shown, among the pages appended, scrolling a virtualizing view to it, or among +the items a virtualizing view draws, which `ScrollToItemAsync` reaches first where the host +knows the index. The item takes the focus and the collection's tab stop where its view gives +the items the focus, and is scrolled into view alone where it doesn't. The call answers +whether the item took the focus, and a newer call replaces one still waiting. + A view whose markers carry the focus pins the focused item with the items either side of it, so the item an arrow reaches is drawn beside the focused one however far the view has scrolled; the cards keep those neighbors as rows, so a focus moving along a row of cards or diff --git a/docs/features-status.md b/docs/features-status.md index 48d9de18..df22f7c1 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -27,7 +27,7 @@ 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, thirty-two changes fixed, and one already met | +| [A host's requests](#a-hosts-requests) | Four components implemented and one on the roadmap, thirty-three 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 | @@ -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-three changes to components that exist, listed here in the order they are taken, +`FormaCommandPalette` is, and thirty-four 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 | @@ -260,6 +260,7 @@ each with what the code does and its state. | 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 | | A sortable list in another's item | Every `FormaSortableList` on the path of a press on a handle took it, so a press on the handle of a list nested in another's item lifted the outer list's item, and the inner list kept its order. The press is a route on the input router, as the handle's keys are, so the innermost list whose handle it is takes it alone | Fixed | +| A row brought back by its key | `FormaDataView`'s `ScrollToItemAsync` moved a paged view to an index's page and no further, and nothing brought a row on screen with the focus by its key, so a reader coming back to a list landed at its top. `FocusItemAsync` gives the item a key names the focus once the items on their way have arrived, on the page shown, among the pages appended or among the items a virtualizing view draws, and answers whether it took it | Fixed | diff --git a/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.cs b/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.cs index ac7b5acf..f04c71e4 100644 --- a/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.cs +++ b/src/Blazor/Forma.Blazor.DataView/FormaDataView.razor.cs @@ -125,6 +125,11 @@ public sealed partial class FormaDataView : FormaElementBase, IDataViewThe items to show, sorted, counted and paged by the data view itself. /// A new queryable is a new set, which the data view reads again. [Parameter] public IQueryable? Items { get; set; } @@ -892,6 +897,11 @@ protected override async Task OnAfterRenderAsync(bool firstRender) _isPageHeightHeld = false; await _heightReservation.ReleaseAsync(); } + + if (_hasLoaded && !_isBusy && !_isLoadingMore && _hasSelectionAnswered) + { + _settledSignal.TrySetResult(); + } } /// Reads the items being shown again. @@ -927,6 +937,71 @@ public async Task ScrollToItemAsync(int index, CancellationToken cancellationTok } } + /// Brings the item keyed on screen and gives it the focus, once the items on their way have arrived. + /// + /// The item is looked for on the page shown, among the pages appended, or among the items a virtualizing view draws, which an item scrolled + /// to by becomes; an item drawn without a marker, where the items take no focus, is scrolled to alone. A + /// newer call replaces one still waiting. + /// + /// The item's key, as gives it. + /// Canceled when the focus is no longer wanted. + /// Whether the item took the focus. + public async Task FocusItemAsync(object key, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + + var request = ++_focusRequest; + + if (!RendererInfo.IsInteractive) + { + return false; + } + + await _settledSignal.Task.WaitAsync(cancellationToken); + + if (IsDisposed || request != _focusRequest) + { + return false; + } + + var index = IndexOfKey(key); + + // A view drawing the items the data view holds draws every one of them, so a key among neither names nothing on screen. + if (index < 0 && !IsVirtualizing && !_itemTokens.TryGetToken(key, out _)) + { + return false; + } + + if (index >= 0 && ActivePositions is { } positions) + { + await positions.ScrollToPositionAsync(index, cancellationToken); + } + + return request == _focusRequest && await _selectionInteraction.RevealItemAsync(_itemTokens.GetToken(key)); + } + + private int IndexOfKey(object key) + { + for (var index = 0; index < _items.Count; index++) + { + if (Equals(ItemKey(_items[index]), key)) + { + return index; + } + } + + return -1; + } + + // A load or an append starting holds a host's focus until the items it brings arrive. + private void HoldFocusRequests() + { + if (_settledSignal.Task.IsCompleted) + { + _settledSignal = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + } + /// /// While the data view appends, a slice is read from the items loaded. public ValueTask> LoadSliceAsync(int startIndex, int count, CancellationToken cancellationToken) @@ -959,6 +1034,7 @@ private async Task AppendAsync() var token = run?.Token ?? CancellationToken.None; _isAppendFailed = false; _isLoadingMore = true; + HoldFocusRequests(); await NotifyStateAsync(); try @@ -1906,6 +1982,9 @@ protected override async ValueTask DisposeAsyncCore() await _selectionInteraction.DisposeAsync(); await _heightReservation.DisposeAsync(); _selfReference?.Dispose(); + + // A host's focus still waiting for the items ends with nothing to focus. + _settledSignal.TrySetResult(); await base.DisposeAsyncCore(); } @@ -2189,6 +2268,7 @@ private async Task LoadAsync(bool asksNodesAgain = false) var cancellation = _loadCancellation = new CancellationTokenSource(); var source = (object?)Items ?? ItemsProvider; _isBusy = true; + HoldFocusRequests(); _ = AnnounceLoadingAsync(cancellation); _loadedPage = _page; _loadedPageSize = PageSize; diff --git a/src/Blazor/Forma.Blazor.DataView/Interop/DataViewJsonContext.cs b/src/Blazor/Forma.Blazor.DataView/Interop/DataViewJsonContext.cs new file mode 100644 index 00000000..5c91133e --- /dev/null +++ b/src/Blazor/Forma.Blazor.DataView/Interop/DataViewJsonContext.cs @@ -0,0 +1,9 @@ +namespace Forma.Blazor.Components.DataView.Interop; + +using System.Text.Json; +using System.Text.Json.Serialization; + +/// What the data view's scripts answer, read with the web's defaults through generated code rather than reflection. +[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] +[JsonSerializable(typeof(bool))] +internal sealed partial class DataViewJsonContext : JsonSerializerContext; diff --git a/src/Blazor/Forma.Blazor.DataView/Interop/SelectionInteraction.cs b/src/Blazor/Forma.Blazor.DataView/Interop/SelectionInteraction.cs index 32ebe2be..fcbb0be8 100644 --- a/src/Blazor/Forma.Blazor.DataView/Interop/SelectionInteraction.cs +++ b/src/Blazor/Forma.Blazor.DataView/Interop/SelectionInteraction.cs @@ -60,6 +60,12 @@ public ValueTask AttachAsync(ElementReference container, DotNetObj public ValueTask FocusItemAsync(int request, int position) => InvokeAsync("focusItem", request, position); + /// Brings the item names on screen once it is drawn, and lands the focus on its marker. + /// The item's token. + /// Whether the focus landed on the item. + public async ValueTask RevealItemAsync(int token) + => await InvokeAsync("revealItem", DataViewJsonContext.Default.Boolean, token); + /// Lets go of a move asked of the owner, which it can no longer answer. public ValueTask CancelSeekAsync() => InvokeAsync("cancelSeek"); diff --git a/src/Blazor/Forma.Blazor.DataView/ItemTokenTable.cs b/src/Blazor/Forma.Blazor.DataView/ItemTokenTable.cs index 8783ab9d..3d3eda2c 100644 --- a/src/Blazor/Forma.Blazor.DataView/ItemTokenTable.cs +++ b/src/Blazor/Forma.Blazor.DataView/ItemTokenTable.cs @@ -75,6 +75,27 @@ public int GetToken(object key, TItem item, object? view = null) return token; } + /// The token for , held while the table lasts, which the item takes once a view draws it. + /// The item's key. + public int GetToken(object key) + { + if (!_tokensByKey.TryGetValue(key, out var token)) + { + token = _nextToken++; + _tokensByKey[key] = token; + } + + _heldKeys.Add(key); + + return token; + } + + /// Finds the token of a key a view drew. + /// The item's key. + /// The token the key's item is drawn with. + public bool TryGetToken(object key, out int token) + => _tokensByKey.TryGetValue(key, out token); + /// How many items the table holds a token for. public int Count => _itemsByToken.Count; diff --git a/src/Blazor/Forma.Blazor.DataView/README.md b/src/Blazor/Forma.Blazor.DataView/README.md index 0e0654e4..5375c296 100644 --- a/src/Blazor/Forma.Blazor.DataView/README.md +++ b/src/Blazor/Forma.Blazor.DataView/README.md @@ -311,6 +311,29 @@ item that cannot be selected activating it, and the switch keeps the focus on th ``` +`FocusItemAsync` brings the item a key names back on screen with the focus once the items on their +way have arrived, so a reader coming back to a list lands on the item they opened. It looks on the +page shown, among the pages appended, or among the items a virtualizing view draws, which +`ScrollToItemAsync` reaches first where the host knows the index, and answers whether the item took +the focus: + +```razor + + + + +@code { + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender && _openedIssueId is { } id) + { + await _list!.FocusItemAsync(id); + } + } +} +``` + Four rules, each a function of the item, say what an item may do. `IsItemDisabled` mutes an item and takes it out of every selection and activation, `CanSelectItem` keeps an item from being selected while it still activates, `CanActivateItem` keeps it from activating or becoming the current node, diff --git a/src/Blazor/Forma.Blazor.DataView/wwwroot/scripts/SelectionInteraction.js b/src/Blazor/Forma.Blazor.DataView/wwwroot/scripts/SelectionInteraction.js index 0a1a7502..64f6b23f 100644 --- a/src/Blazor/Forma.Blazor.DataView/wwwroot/scripts/SelectionInteraction.js +++ b/src/Blazor/Forma.Blazor.DataView/wwwroot/scripts/SelectionInteraction.js @@ -512,6 +512,28 @@ class SelectionInteraction { }); } + /** + * Brings the item a token names on screen once it is drawn and lands the focus on its marker, letting go of a move asked of the owner; + * an item drawn with no marker, its view taking no focus on its items, is scrolled to alone. + * @param {number} token The item's token. + * @returns {Promise} Whether the focus landed on the item, false where it wasn't drawn in time or a newer wait replaced this one. + */ + revealItem(token) { + this.#cancelSeek(); + + return new Promise(resolve => this.#whenDrawn(() => this.#itemWithToken(token), item => { + const marker = this.#ownMarker(item); + + if (marker) { + this.#focusMarker(marker, this.#markers()); + } else { + item.scrollIntoView({ block: 'nearest' }); + } + + resolve(marker !== null); + }, () => resolve(false))); + } + /** Lets go of a move asked of the owner, which the owner can no longer answer. */ cancelSeek() { this.#cancelSeek(); @@ -1166,40 +1188,48 @@ class SelectionInteraction { this.#stopWaiting = null; } - // Hands over the marker the finder names once it is drawn, giving up after a while or when the reader moves on; a newer wait - // replaces this one, and this one's own end stops it alone. - #whenDrawn(find, land) { + // Hands over what the finder names once it is drawn, giving up after a while or when the reader moves on, which it tells the abandon + // callback; a newer wait replaces this one, and this one's own end stops it alone. + #whenDrawn(find, land, abandon = () => {}) { this.#stopWaiting?.(); this.#stopWaiting = null; - const marker = find(); + const found = find(); - if (marker) { - land(marker); + if (found) { + land(found); return; } const observer = new MutationObserver(() => { - const drawnMarker = find(); + const drawn = find(); - if (drawnMarker) { + if (drawn) { stop(); - land(drawnMarker); + land(drawn); } }); - const timer = setTimeout(() => stop(), SeekPatience); + const timer = setTimeout(() => giveUp(), SeekPatience); const stop = () => { observer.disconnect(); clearTimeout(timer); - if (this.#stopWaiting === stop) { + if (this.#stopWaiting === giveUp) { this.#stopWaiting = null; } }; + const giveUp = () => { + stop(); + abandon(); + }; + + // An element a view draws again in place takes its new item's token and position as attributes. + const attributeFilter = [this.#positionAttribute, this.#itemKeyAttribute, this.#keyAttribute].filter(name => name !== null); + observer.observe(this.#target, { childList: true, subtree: true, attributes: true, attributeFilter }); + this.#stopWaiting = giveUp; + } - observer.observe(this.#target, this.#positionAttribute - ? { childList: true, subtree: true, attributes: true, attributeFilter: [this.#positionAttribute] } - : { childList: true, subtree: true }); - this.#stopWaiting = stop; + #itemWithToken(token) { + return this.#itemKeyAttribute === null ? this.#markerWithToken(token) : this.#target.querySelector(`[${this.#itemKeyAttribute}="${token}"]`); } /** The items and the place the key would move the focused one to, the list's end to ask the owner for, or null where there is nowhere to go. */ diff --git a/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor b/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor index 420be3ca..35027a55 100644 --- a/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor @@ -451,6 +451,98 @@ private sealed record Product(int Id, string Name); } + public sealed class FocusingAnItem + { + private static IQueryable CreateProducts(int count) + => Enumerable.Range(1, count).Select(id => new Product(id, $"Product {id}")).AsQueryable(); + + // The selection behavior, whose reveal answers that the focus landed. + private static BunitJSModuleInterop SetUpSelection(FormaDataViewTests ctx) + { + var behavior = ctx.JSInterop.SetupModule("./_content/Forma.Blazor.DataView/scripts/SelectionInteraction.js").SetupModule("attach", _ => true); + behavior.Setup("revealItem", _ => true).SetResult(InteropAnswer.Of(true)); + + return behavior; + } + + private static string? TokenOf(IRenderedComponent cut, string name) + => cut.FindAll("[data-item]").Single(item => item.TextContent.Contains(name, StringComparison.Ordinal)).GetAttribute("data-item"); + + [Fact] + public async Task Should_land_the_focus_on_the_item_keyed_on_the_page_shown() + { + // Arrange — the second page of thirty products, ten to a page + using var ctx = new FormaDataViewTests(); + var behavior = SetUpSelection(ctx); + var cut = ctx.Render( + @ + + ); + cut.WaitForState(() => cut.Markup.Contains("Product 15", StringComparison.Ordinal)); + var engine = cut.FindComponent>(); + + // Act + var isFocused = await engine.InvokeAsync(() => engine.Instance.FocusItemAsync(15)); + + // Assert + Assert.Multiple( + () => Assert.True(isFocused), + () => Assert.Equal(int.Parse(TokenOf(cut, "Product 15")!, CultureInfo.InvariantCulture), Assert.Single(behavior.Invocations["revealItem"]).Arguments[0])); + } + + [Fact] + public async Task Should_answer_that_an_item_off_the_page_shown_took_no_focus() + { + // Arrange — the first page of thirty products, the twenty-fifth on the third + using var ctx = new FormaDataViewTests(); + var behavior = SetUpSelection(ctx); + var cut = ctx.Render( + @ + + ); + cut.WaitForState(() => cut.Markup.Contains("Product 10", StringComparison.Ordinal)); + var engine = cut.FindComponent>(); + + // Act + var isFocused = await engine.InvokeAsync(() => engine.Instance.FocusItemAsync(25)); + + // Assert + Assert.Multiple( + () => Assert.False(isFocused), + () => Assert.Empty(behavior.Invocations["revealItem"])); + } + + [Fact] + public async Task Should_wait_for_the_items_on_their_way_before_looking_for_the_item() + { + // Arrange — a source whose answer the test holds + using var ctx = new FormaDataViewTests(); + var behavior = SetUpSelection(ctx); + var held = new TaskCompletionSource>(); + DataViewItemsProvider provider = _ => new ValueTask>(held.Task); + var cut = ctx.Render( + @ + + ); + var engine = cut.FindComponent>(); + + // Act — asked while the source answers, then the answer arrives + Task focusing = null!; + await engine.InvokeAsync(() => { focusing = engine.Instance.FocusItemAsync(2); }); + var wasWaiting = !focusing.IsCompleted; + await cut.ReleaseAsync(() => held.SetResult(new DataViewPage([.. CreateProducts(3)], 3))); + var isFocused = await focusing; + + // Assert + Assert.Multiple( + () => Assert.True(wasWaiting), + () => Assert.True(isFocused), + () => Assert.Equal(int.Parse(TokenOf(cut, "Product 2")!, CultureInfo.InvariantCulture), Assert.Single(behavior.Invocations["revealItem"]).Arguments[0])); + } + + private sealed record Product(int Id, string Name); + } + public sealed class Seeking { private static IQueryable CreateProducts() => new[] diff --git a/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewReturnCheck.razor b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewReturnCheck.razor new file mode 100644 index 00000000..d0c9ef4e --- /dev/null +++ b/tests/e2e/Components/Forma.Blazor.Browser.Components.Checks/DataView/DataViewReturnCheck.razor @@ -0,0 +1,59 @@ +@page "/{Runtime}/data-view-return" +@using Forma.Blazor.Components.DataView + +@* Thirty rows in a grid, ten to a page, opened on the second with its fifteenth row given the focus, as a reader coming back to the + list finds it, and two hundred rows in a virtualizing grid a box's height, its hundred and fiftieth scrolled to and given the focus + at a press; each writes whether its row took the focus where the check reads it. *@ + + + + + + + +@_pagedResult + +
+ + + + + + + +
+@_scrolledResult + +@code { + private static readonly IQueryable PagedRows = Enumerable.Range(1, 30).Select(id => new Row(id, $"Row {id}")).ToArray().AsQueryable(); + + private static readonly IQueryable ScrolledRows = Enumerable.Range(1, 200).Select(id => new Row(id, $"Row {id}")).ToArray().AsQueryable(); + + private FormaDataView Paged { get; set; } = default!; + + private FormaDataView Scrolled { get; set; } = default!; + + private bool? _pagedResult; + private bool? _scrolledResult; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + _pagedResult = await Paged.FocusItemAsync(15); + StateHasChanged(); + } + } + + private async Task ReturnAsync() + { + await Scrolled.ScrollToItemAsync(149); + _scrolledResult = await Scrolled.FocusItemAsync(150); + } + + // The name each row's element carries, which the check reads the focused row by. + private static IReadOnlyDictionary? NameOf(Row row) + => new Dictionary { ["data-name"] = row.Name }; + + internal sealed record Row(int Id, string Name); +} diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs index d145ab91..4d001064 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/DataViewTests.cs @@ -704,6 +704,52 @@ public async Task Should_keep_the_current_folder_the_open_folders_the_selection_ } } + public sealed class DataViewReturn(BrowserHost host) + { + // The name of the row holding the focus, and whether it stands wholly inside what shows of the box id names, the page where null. + private const string ReadFocusedRow = """ + id => { + const row = document.activeElement; + const bounds = id ? document.getElementById(id).getBoundingClientRect() : { top: 0, bottom: window.innerHeight }; + const box = row.getBoundingClientRect(); + const isInView = box.top >= bounds.top - 0.5 && box.bottom <= bounds.bottom + 0.5; + return `${row.getAttribute('data-name') ?? row.tagName}, ${isInView ? 'in view' : 'out of view'}`; + } + """; + + [Theory] + [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_give_the_focus_to_the_row_a_reader_comes_back_to_on_its_page(string runtime) + { + // Arrange — the page asks for the fifteenth row, on the second page, as it opens + var (context, page) = await OpenAsync(host, runtime, "data-view-return"); + await using var _ = context; + + // Act + await Assertions.Expect(page.Locator("#paged-result")).ToHaveTextAsync("True"); + + // Assert + Assert.Equal("Row 15, in view", await page.EvaluateAsync(ReadFocusedRow, null)); + } + + [Theory] + [MemberData(nameof(Runtimes), MemberType = typeof(ComponentChecks))] + public async Task Should_give_the_focus_to_a_row_scrolled_to_in_a_virtualizing_view(string runtime) + { + // Arrange + var (context, page) = await OpenAsync(host, runtime, "data-view-return"); + await using var _ = context; + await Assertions.Expect(page.Locator("#paged-result")).ToHaveTextAsync("True"); + + // Act — the hundred and fiftieth row, far below what the box shows + await page.Locator("#return").ClickAsync(); + await Assertions.Expect(page.Locator("#scrolled-result")).ToHaveTextAsync("True"); + + // Assert + Assert.Equal("Row 150, in view", await page.EvaluateAsync(ReadFocusedRow, "box")); + } + } + public sealed class DataViewPage(BrowserHost host) { [Theory] diff --git a/tests/scripts/dataview/SelectionInteraction.test.js b/tests/scripts/dataview/SelectionInteraction.test.js index deb78ed8..39d40547 100644 --- a/tests/scripts/dataview/SelectionInteraction.test.js +++ b/tests/scripts/dataview/SelectionInteraction.test.js @@ -621,6 +621,80 @@ describe('SelectionInteraction', () => { }); }); + describe('revealing an item the owner names', () => { + /** @type {HTMLElement} */ + let list; + const itemOf = key => document.querySelector(`[data-item="${key}"]`); + const options = extra => ({ owner, itemSelector: '[data-item]', itemKeyAttribute: 'data-item', selects: false, moves: true, ...extra }); + + beforeEach(() => { + document.body.insertAdjacentHTML('beforeend', ` +
+
One
+
Two
+
Three
+
`); + list = document.querySelector('#list'); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('lands the focus on a drawn item and makes it the tab stop', async () => { + const handle = attachSelection(list, options()); + + const isFocused = await handle.revealItem(3); + + expect(isFocused).toBe(true); + expect(document.activeElement).toBe(itemOf(3)); + expect([1, 2, 3].map(key => itemOf(key).tabIndex)).toEqual([-1, -1, 0]); + }); + + it('lands the focus on an item once it is drawn', async () => { + const handle = attachSelection(list, options()); + + const revealed = handle.revealItem(9); + list.insertAdjacentHTML('beforeend', '
Nine
'); + + expect(await revealed).toBe(true); + expect(document.activeElement).toBe(itemOf(9)); + }); + + it('scrolls to an item drawn with no marker, answering that it took no focus', async () => { + list.insertAdjacentHTML('beforeend', '
Five
'); + const handle = attachSelection(list, options()); + itemOf(5).scrollIntoView = vi.fn(); + + const isFocused = await handle.revealItem(5); + + expect(isFocused).toBe(false); + expect(itemOf(5).scrollIntoView).toHaveBeenCalledOnce(); + expect(document.activeElement).not.toBe(itemOf(5)); + }); + + it('answers that an item never drawn took no focus once it stops waiting', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const handle = attachSelection(list, options()); + + const revealed = handle.revealItem(42); + vi.advanceTimersByTime(3000); + + expect(await revealed).toBe(false); + }); + + it('answers that a reveal a newer one replaced took no focus', async () => { + const handle = attachSelection(list, options()); + + const replaced = handle.revealItem(42); + const isFocused = await handle.revealItem(2); + + expect(await replaced).toBe(false); + expect(isFocused).toBe(true); + expect(document.activeElement).toBe(itemOf(2)); + }); + }); + describe('holding an item', () => { /** @type {HTMLElement} */ let list; From 30de141c6a2b412e67dc30fd50e3adfbf57bd421 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:26:27 +0200 Subject: [PATCH 05/10] docs(domql): name the data view's reveal command and the sortable list's routed press in the replacement plan --- docs/forma-javascripts-domql-replacement.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/forma-javascripts-domql-replacement.md b/docs/forma-javascripts-domql-replacement.md index e2b58e4d..b8ecb683 100644 --- a/docs/forma-javascripts-domql-replacement.md +++ b/docs/forma-javascripts-domql-replacement.md @@ -110,7 +110,7 @@ The Forma modules this produces, each beside the capability it exposes: | `FormaVirtualizer`, which `VirtualizerDomqlModule` declares | `virtualizer` (a maintained member of a nullable type with its own observation type); `reveal`, `scrollTo` (once) | `Virtualize.js` | | `FormaAssets`, `FormaPrint`, `FormaEmbeds` | `loadModule`, `loadStyle`, `loadSprite`; `printDocument`, `composeDocument`, `composePage`; `activateEmbed` (once) | `Asset.js`, `Print.js`, `Embedding.js` | | `FormaRichText` | The view `richText`: `edit` (continuous), `execute`, `commit`, `beginLinkDialog` (commands), `changes`, `activations` (sources), `selection` (a member reading the state `edit` offers); `blockAlignment` (continuous, on the gutter) | `RichTextEditor.js` and its modules, `BlockAlignment.js` | -| `FormaDataView` | The view `dataView`: `selection` (continuous), `selections` (source), `focusItem`, `cancelSeek` (commands); the view `dataGrid`: `wantedWidths` (a maintained member answering `List?`, with its own observation type) | `SelectionInteraction.js`, `ColumnFit.js` | +| `FormaDataView` | The view `dataView`: `selection` (continuous), `selections` (source), `focusItem`, `revealItem`, `cancelSeek` (commands); the view `dataGrid`: `wantedWidths` (a maintained member answering `List?`, with its own observation type) | `SelectionInteraction.js`, `ColumnFit.js` | | The Showcase's own | `readingPlace` with the command `reveal` | `ReadingPlace.js` | ## Decisions the replacement rests on @@ -224,7 +224,7 @@ DOMQL's [extension contract](https://github.com/FormaUI/DOMQL/blob/main/docs/fea | --- | --- | --- | --- | --- | | C1 | Occurrences a behavior offers, through its module's event sources, which hear every instance for their owner on their receiver | [D49] | `InputRouter.js`, `DropZone.js`, `ReorderInteraction.js`, `Wheel.js`, `Frame.js`, `Splitter.js`, `SelectionInteraction.js`, `RichTextEditor.js`, `CultureCoordinator.js`; `Owner.js`'s reports retire into it | — | | C2 | State a behavior offers, read by its module's members and followed through the `behavior` observation | [D52] | `RichTextEditor.js`: the selection `edit` offers; `InputRouter.js`: `inputState` | `Frame.js`, its placement read as state rather than heard; `ColumnFit.js`, as a behavior a watch reads | -| C3 | Commands to a running behavior, reaching the latest instance for their owner on their receiver, and failing with `DOMQL5016` where none runs | [D48] | `AnchoredPopover.js` (`open`, `close`), `Window.js` (`raise`, `refocus`), `Frame.js` (`measure`, `commit`), `FilePreview.js` (`show`), `SelectionInteraction.js` (`focusItem`, `cancelSeek`), `RichTextEditor.js` (`execute`, `setHtml`, `beginLinkDialog`), `CultureCoordinator.js` (`requestCulture`, `reportCultureLanding`, `followCulture`), `ReadingPlace.js` (`reveal`) | — | +| C3 | Commands to a running behavior, reaching the latest instance for their owner on their receiver, and failing with `DOMQL5016` where none runs | [D48] | `AnchoredPopover.js` (`open`, `close`), `Window.js` (`raise`, `refocus`), `Frame.js` (`measure`, `commit`), `FilePreview.js` (`show`), `SelectionInteraction.js` (`focusItem`, `revealItem`, `cancelSeek`), `RichTextEditor.js` (`execute`, `setHtml`, `beginLinkDialog`), `CultureCoordinator.js` (`requestCulture`, `reportCultureLanding`, `followCulture`), `ReadingPlace.js` (`reveal`) | — | | C4 | The owner's identity, an `owner` every operation takes | [D47] | Every behavior with occurrences or commands: `InputRouter.js`, where several registrations share a scope, `DropZone.js`, `ReorderInteraction.js`, `Wheel.js`, `Splitter.js`, `Frame.js`, `AnchoredPopover.js`, `Window.js`, `FilePreview.js`, `SelectionInteraction.js`, `RichTextEditor.js`, `CultureCoordinator.js`, `ReadingPlace.js` | — | | C5 | DOMQL's observations and frame schedule for module code, `env.observe` and `env.frame`, a frame's writes before its reads | [D53] | — | Sharing DOMQL's pools: `AnchoredPopover.js`, `Frame.js`, `Virtualize.js`, `RovingFocus.js`, `FocusRecovery.js`, `ScrollButtons.js`, `SelectionInteraction.js`, `BlockAlignment.js`, `SelectionFollower.js`. `FrameScheduler.js` stays for the plain classes (F2) | | C6 | Queries from module code, `env.domql` | [D54] | The modules that hold a rendered target through an owned write ([below](#owned-writes-beside-blazors-render)) | `ScrollButtons.js`, `RovingFocus.js` | @@ -626,7 +626,7 @@ Product scripts of `Forma.Blazor.DataView`, `Forma.Blazor.Explorer` and `Forma.B | `ColumnFit.js` | 80 | `FormaDataGrid` | **Watch** `table { availableWidth = (try it.parent as Element)?.clientSize?.width, columns = it:dataGrid.wantedWidths({ attribute = "data-column", measuringClass = "forma-data-grid-measuring" }) { key = it.key, width = it.width } }`, accepting partial observation. `wantedWidths` is a maintained member answering `List?`, nullable as DOMQL `1.0.0-beta.2` requires of a member reading maintained values (NEXO4071), whose observation type, the data view module's, observes the boxes and the content through `env.observe`. It measures with `env.measureUnder(table, { class: measuringClass }, read)` as it starts and as it samples, which DOMQL's own observers never hear. The host layer passes on no snapshot whose `availableWidth` or `columns` is null, as today's script reports nothing for a table out of the document; C#'s `ColumnFitReport` holds neither as null. Its fallback is a continuous execution whose state a watch reads | A transient measurement ([D55]); `env.observe` ([D53]); its fallback, state a behavior offers ([D52]) | Data view | | `GridColumns.js` | 60 | `FormaDataCards` | **Watch** `ruler { columns = it.grid?.columns.count, cardSize = cards.style["--forma-data-cards-size"] }`, `cards` bound to `FormaDataCards`' root, whose rendered `style` carries `--forma-data-cards-size`, accepting partial observation; reading the card size follows a change the script misses. C# clamps the count to 1, since `grid` answers no track for a template of `none`. The host layer passes on no null count, which `grid` answers while the ruler has no layout box, as today's script reports nothing for a ruler out of the document | — | Data view | | `HeightReservation.js` | 60 | `FormaDataView` | **Watch** of the table's, its header's and its tallest item row's heights, accepting partial observation. C# turns them into the region's `min-block-size` by today's rule: a full page's height held outright, a short page's projected only while nothing is held. Below | Selectors observed for what they read ([D26]), so the selection's `tabindex` writes evaluate nothing | Data view | -| `SelectionInteraction.js` | 645 | `FormaDataView`, over every view | **Continuous execution** `region:dataView.selection({ itemSelector = "[data-item]", itemKeyAttribute = "data-item", controlSelector = "[data-item-control]", selects = selects, moves = moves, positionAttribute = "data-item-position", seeks = seeks })`, its modes bound, so `update({ region, selects, moves, seeks })` replaces today's detach and attach on a mode change: an update replaces the bindings, never the literals a text writes. It offers one source, `region:dataView.selections() { kind = it.kind, token = it.token, tokens = it.tokens, from = it.from, to = it.to, additive = it.additive, request = it.request, last = it.last, mode = it.mode }`, a seek carrying its anchor's position in `from`, null unless it extends, as `HandleSeekAsync` takes it, keeping its five reports in order, delivered inside the press's or the key's dispatch: a select, a range by tokens, a range by positions, a seek and an activation. A range by tokens carries every token it spans, so it reaches C# through the [browser transfer](browser-transfer-design.md). The commands `region:dataView.focusItem({ request = request, position = position })` and `region:dataView.cancelSeek()` reach it, and reject with `DOMQL5016` once it has ended, where today's call answers `false` | Occurrences ([D49]) inside the dispatch ([D51]), commands ([D48]), the owner ([D47]); `env.observe` and `env.frame` if it chooses ([D53]) | Data view | +| `SelectionInteraction.js` | 645 | `FormaDataView`, over every view | **Continuous execution** `region:dataView.selection({ itemSelector = "[data-item]", itemKeyAttribute = "data-item", controlSelector = "[data-item-control]", selects = selects, moves = moves, positionAttribute = "data-item-position", seeks = seeks })`, its modes bound, so `update({ region, selects, moves, seeks })` replaces today's detach and attach on a mode change: an update replaces the bindings, never the literals a text writes. It offers one source, `region:dataView.selections() { kind = it.kind, token = it.token, tokens = it.tokens, from = it.from, to = it.to, additive = it.additive, request = it.request, last = it.last, mode = it.mode }`, a seek carrying its anchor's position in `from`, null unless it extends, as `HandleSeekAsync` takes it, keeping its five reports in order, delivered inside the press's or the key's dispatch: a select, a range by tokens, a range by positions, a seek and an activation. A range by tokens carries every token it spans, so it reaches C# through the [browser transfer](browser-transfer-design.md). The commands `region:dataView.focusItem({ request = request, position = position })`, `region:dataView.revealItem({ token = token })`, answering whether the focus landed on the item once it is drawn, and `region:dataView.cancelSeek()` reach it, and reject with `DOMQL5016` once it has ended, where today's call answers `false` | Occurrences ([D49]) inside the dispatch ([D51]), commands ([D48]), the owner ([D47]); `env.observe` and `env.frame` if it chooses ([D53]) | Data view | | `Breakpoint.js` | 57 | `FormaExplorerCommandArea` | **Watch** `rows.style["--forma-explorer-header-layout"]`, accepting partial observation. `style` answers null for an empty value, which C# reads as the wide tier, as it reads today's empty string | — | Explorer | | `ReadingPlace.js` | 188 | The Showcase's sidebar | **Continuous execution** of the Showcase's own module, `pages:readingPlace({ links = ".culture-switcher a", sections = ".demo-section", current = ":scope > a.active" })`, with `pages:reveal()` a command. Its note is written inside the click before a full navigation unloads the page, and its hold reacts to every change for two seconds, so both stay inside, with their session storage. The sidebar runs it today through a `JSEnvironment` of its own, with no Forma context, which it needs for a session and an owner the host layer can run it for ([findings](#the-explorer-and-the-showcase)) | Commands ([D48]), the owner ([D47]) | Showcase | @@ -691,7 +691,7 @@ Reading the scripts turned these up. None was reproduced, and each is Forma's to ### Input acted on outside the input router -- **Still so:** `DragGesture.js` without an `action`, as `ReorderInteraction.js`, `Frame.js` and `SelectionFollower.js` use it; `Frame.js`'s own `keydown`; `Dialog.js`'s scrim `click`. +- **Still so:** `DragGesture.js` without an `action`, as `Frame.js` and `SelectionFollower.js` use it; `Frame.js`'s own `keydown`; `Dialog.js`'s scrim `click`. - **New:** `DropZone.js` cancels `dragenter` in a raw listener; `SelectionFollower.js` nudges with the arrow keys in its own `keydown`; `RichTextEditor.js` cancels `dblclick` itself, though the router routes `dblclick`; `FormaBreadcrumb` cancels `dragover` on each crumb through Blazor's `@ondragover:preventDefault`, beside the explorer sidebar's routed drop zone, and its C# write of `DropEffect` never reaches the browser. ### The input router From 55027af41b2246fc353ad1453229ef2cdd7b8403 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:17:32 +0200 Subject: [PATCH 06/10] docs(domql): reach DOMQL from C# through DOMQL.NET --- docs/dom-watcher-engine-design.md | 130 +++++++++--------- .../dom-watcher-engine-implementation-plan.md | 4 +- docs/features-status.md | 2 +- docs/forma-javascripts-domql-replacement.md | 107 +++++++------- docs/repository-structure.md | 4 +- 5 files changed, 129 insertions(+), 118 deletions(-) diff --git a/docs/dom-watcher-engine-design.md b/docs/dom-watcher-engine-design.md index 32a2a766..ccb84be5 100644 --- a/docs/dom-watcher-engine-design.md +++ b/docs/dom-watcher-engine-design.md @@ -1,6 +1,6 @@ # Forma DOM Watcher and Engine Design -`DomEngine` and `DomWatcher` are the bridge between C# components and the browser. A component goes through them whenever it calls a browser function, asks how the document looks, listens for something that happened, or establishes behavior that runs on in the browser: it says "do this", "tell me the current state" or "let me know when this happens", whichever capability carries out the work. Shared imports, registrations, callbacks and resource management sit beneath that one model, so no component repeats them. +`DomEngine` and `DomWatcher` are the bridge between C# components and the browser. A component goes through them whenever it calls a browser function, asks how the document looks, listens for something that happened, or establishes behavior that runs on in the browser: it says "do this", "tell me the current state" or "let me know when this happens", whichever capability carries out the work. [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), DOMQL's own .NET host, sits beneath that one model with its connection, its owners and their handles, so no component repeats them. The [implementation plan](dom-watcher-engine-implementation-plan.md) holds the delivery order, the measurements and the gates. @@ -13,11 +13,11 @@ The [implementation plan](dom-watcher-engine-implementation-plan.md) holds the d | Two entry points | `DomWatcher` reads, watches and listens; `DomEngine` acts and establishes behavior, and borrows the watcher. | | One request model | A component names its targets and the facts it needs of them in one DOMQL query, and one snapshot answers, read once or watched. | | Typed requests | Actions and behaviors are typed, and so are their results; a snapshot maps onto a type the component names, and no single method takes every request. | -| Loading by request | A consumer loads only the capabilities its requests require. Observation requests that do not name input load no input integration, and querying or subscribing to input loads the input integration it requires. Observation alone establishes no routing behavior, and watcher-only requests leave the engine unloaded. | +| Loading by request | A consumer loads only the capabilities its requests require. Observation requests that do not name input load no input integration, and querying or subscribing to input loads the input integration it requires. Observation alone establishes no routing behavior, and watcher-only requests load no behavior's module. | | Shared lifetime | Watches and behaviors reconcile requested state against successfully applied state. | -| One notification channel | One callback receiver per owner delivers snapshots and occurrences and surfaces failures. | +| One connection | DOMQL.NET's connection, one for each browser runtime, carries every request, snapshot, occurrence and failure, and each component's owner ends what the component started. | | Managed ownership | Blazor keeps rendering, application state, collections, validation and workspace policy. | -| Packaging | DOMQL is a JavaScript library in the sibling [DOMQL](https://github.com/FormaUI/DOMQL) repository, published as the package `formaui-net.DOMQL`, which carries it as one bundled file served from `_content/domql/domql.js`, and references neither interop assembly. The API lives in `Forma.Framework.Browser.Interop`, served from `_content/forma/browser`; `Forma.Framework.Browser.Blazor.Server` connects a Server circuit's reconnection to it. | +| Packaging | DOMQL is a JavaScript library in the sibling [DOMQL](https://github.com/FormaUI/DOMQL) repository, published as the package `formaui-net.DOMQL`, which carries it as one bundled file served from `_content/domql/domql.js`, and references neither interop assembly. DOMQL.NET, DOMQL's own .NET host, is the sibling [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) repository's package `formaui-net.DOMQL.NET`, which serves its browser module from `_content/domql.net`. The API lives in `Forma.Framework.Browser.Interop`, served from `_content/forma/browser`; `Forma.Framework.Browser.Blazor.Server` connects a Server circuit's reconnection to it. | The watcher and the engine provide concrete browser capabilities through that model. Each capability arrives with a consumer that needs it. @@ -47,13 +47,13 @@ The browser foundation stands on five pillars, each one architectural responsibi | Pillar | Responsibility | | --- | --- | -| `DomWatcher.js` | Reads, watches and listens: runs queries, keeps watches current, and delivers snapshots and occurrences | -| `DomEngine.js` | Runs actions and establishes behaviors | -| `domql.js` | Defines requests, queries, actions and behaviors: parsing, definitions, validation and evaluation, over the vocabulary and the modules that extend it | +| `DomWatcher` | Reads, watches and listens: makes a component's queries, watches and subscriptions through its DOMQL.NET owner, and hands it their snapshots and occurrences | +| `DomEngine` | Runs actions and establishes behaviors, through the same owner | +| `domql.js` | Defines requests, queries, actions and behaviors: parsing, definitions, validation and evaluation, over the vocabulary and the modules that extend it; and the connection DOMQL.NET opens, which carries them across | | `Virtualizer.js` | Virtualization's browser measurement, rendered range, pinning and scrolling | | `InputRouter.js` | Input ownership, route matching, and the actions and dismissals routes report | -C# reaches the foundation through the engine and the watcher, and JavaScript uses it directly. Every component's browser interop and C#–JavaScript communication goes through it, reusing its transport, subscriptions, resource management and failure handling rather than a mechanism of its own. A component can still own scripts for its own algorithms, as the composer's rich-text editor does; they build on the pillars wherever they apply, and contribute an extension where they need a capability the foundation does not yet offer. The pillars grow as requirements arrive, and a new pillar takes a distinct responsibility that fits none of the existing ones. +C# reaches the foundation through the engine and the watcher, and JavaScript uses DOMQL directly. Every component's browser interop and C#–JavaScript communication goes through it, reusing DOMQL.NET's transport, subscriptions, resource management and failure handling rather than a mechanism of its own. A component can still own scripts for its own algorithms, as the composer's rich-text editor does; they build on the pillars wherever they apply, and contribute an extension where they need a capability the foundation does not yet offer. The pillars grow as requirements arrive, and a new pillar takes a distinct responsibility that fits none of the existing ones. The input router and the virtualizer stay independently usable, each with its own API and its own algorithms, and take full part in the unified interface through a DOMQL module that exposes them: `InputRouterDomqlModule` and `VirtualizerDomqlModule`, registered with `Domql.registerModule`. A module exposes four kinds of capability: @@ -68,17 +68,20 @@ DOMQL describes these requests and validates them against the module's declarati ### DOMQL's package -`formaui-net.DOMQL` holds DOMQL itself, a JavaScript library in a repository of its own, which [the repository's structure](repository-structure.md) says how this one references: parsing, fluent construction and the shared definition; vocabulary registration and validation; the contracts for state, occurrences, actions and behaviors; and the abstract execution context those contracts take. Browser-specific implementations, the managed interop transport, component ownership and the concrete watcher and engine stay outside it, and its contracts name none of them, so every dependency points toward it. +`formaui-net.DOMQL` holds DOMQL itself, a JavaScript library in a repository of its own, which [the repository's structure](repository-structure.md) says how this one references: parsing, fluent construction and the shared definition; vocabulary registration and validation; the contracts for state, occurrences, actions and behaviors; the abstract execution context those contracts take; and the connection a host across a boundary speaks. Browser-specific implementations, component ownership and the concrete watcher and engine stay outside it, and its contracts name none of them, so every dependency points toward it. + +`formaui-net.DOMQL.NET` holds DOMQL.NET, DOMQL's own host of that connection in .NET, in a repository of its own: one `DomqlConnection` for each browser runtime, registered by `AddDomql`; owners, whose disposal ends every operation they started; watches keeping a typed copy of their result; subscriptions; executions; and failures carrying DOMQL's codes. It depends on `formaui-net.DOMQL` alone, for the bundle its browser module imports, and names nothing of Forma's. | Project | References | | --- | --- | | `Forma.DOMQL`, the package `formaui-net.DOMQL` | Neither interop assembly | +| `Forma.DOMQL.NET`, the package `formaui-net.DOMQL.NET` | `formaui-net.DOMQL` | | `Forma.Framework.Input.Interop` | `formaui-net.DOMQL` | | `Forma.Framework.Browser` | Neither interop assembly | -| `Forma.Framework.Browser.Interop` | `formaui-net.DOMQL`, `Forma.Framework.Browser` and `Forma.Framework.Input.Interop` | +| `Forma.Framework.Browser.Interop` | `formaui-net.DOMQL.NET`, `Forma.Framework.Browser` and `Forma.Framework.Input.Interop` | | A product's integration | `formaui-net.DOMQL` and the capabilities it uses | -`InputRouterDomqlModule` lives beside the router in the input assembly and implements DOMQL's contracts without referencing the browser interop assembly. The assembly graph and the import graph are separate: the module is a JavaScript module of its own, so using the router alone never loads DOMQL. The registry holds definitions alone; component instances, circuit references and subscriptions stay in the sessions that own them. A library that should carry no DOMQL dependency at all exposes its capabilities through an integration package instead, and one such package can serve several capabilities. +`InputRouterDomqlModule` lives beside the router in the input assembly and implements DOMQL's contracts without referencing the browser interop assembly. The assembly graph and the import graph are separate: the module is a JavaScript module of its own, so using the router alone never loads DOMQL. The registry holds definitions alone; component instances, circuit references and subscriptions stay with the connection and the owners that hold them. A library that should carry no DOMQL dependency at all exposes its capabilities through an integration package instead, and one such package can serve several capabilities. ## Public object model @@ -94,30 +97,25 @@ The same query is read once or watched. A read makes one crossing and returns on A query is written in [DOMQL](https://github.com/FormaUI/DOMQL/blob/main/spec/README.md), with its targets as parameters, and the browser evaluates it for C# and JavaScript alike, so both get one meaning. -A component writes its query as DOMQL text and names the snapshot's type, so reading and watching name no type again: +A component writes its query as DOMQL text and names the snapshot's type, through DOMQL.NET's `DomqlQuery`, so reading and watching name no type again: ```csharp private sealed record ViewportState(double? Width, bool? HasFocus); -var query = Domql.Parse( - """ - @viewport { - width: size.width, - hasFocus: focus.within - } - """, - ("viewport", _viewport)); +private static readonly DomqlQuery Viewport = DomqlQuery.Create( + "viewport { width = it.layoutSize?.inline, hasFocus = it.focusWithin }", + ComponentJsonContext.Default.ViewportState); // Read it once. -ViewportState state = await Context.DomWatcher.ReadAsync(query); +ViewportState state = await Context.DomWatcher.ReadAsync(Viewport, new Dictionary { ["viewport"] = _viewport }); // Or watch it: the first snapshot, then each change. -_watch = await Context.DomWatcher.WatchAsync(query, HandleStateAsync); +_watch = await Context.DomWatcher.WatchAsync(Viewport, new Dictionary { ["viewport"] = _viewport }, HandleStateAsync); ``` -A query parsed without a type is a `DomqlQuery`, read as a `DomqlSnapshot` with structured access to its values, and `Domql.Create` and `Domql.TryParse` complete the set, as DOMQL defines. The definition is what crosses to the browser, and an element target is bound as an `ElementReference` through the bridge, beside the definition and never inside it. +A query made without a type keeps its result's JSON, as DOMQL.NET defines. The text is checked in the browser by the first request that carries it, and an element target is bound as an `ElementReference`, beside the text and never inside it. -C# keeps each watch's cached state, applies every change set the browser sends to it, and maps a new snapshot that reuses the unchanged parts of the last, so `Current` never changes under its holder. A typed query maps its snapshot onto `T`: its fields onto constructor parameters by name regardless of case, a nested shape onto a nested type, a list onto a read-only list, and an unavailable fact onto a nullable member. A mapping that does not fit is a failure, reported through the watcher's failure path and never filled with a default value: +DOMQL.NET keeps each watch's copy, applies every change set the browser sends to it, and maps the copy onto a new snapshot, so `Current` never changes under its holder. A typed query maps its snapshot onto `T` through the source-generated type information the component names: its fields onto constructor parameters by name regardless of case, a nested shape onto a nested type, a list onto a read-only list, and an unavailable fact onto a nullable member. A mapping that does not fit is a failure, DOMQL.NET's `DOMQL5028`, reported through the watcher's failure path while the current snapshot stands, and never filled with a default value. The serializer options Forma's type information carries make each of these one: - Two fields whose names differ only in case, which a mapping that matches names regardless of case cannot tell apart. - A field with no constructor parameter of its name, or a constructor parameter with no field. @@ -125,20 +123,20 @@ C# keeps each watch's cached state, applies every change set the browser sends t - A number meeting an integral destination it does not fit exactly. -A script reads, watches and listens to a query through the browser watcher directly, with no managed bridge and no callback reference: +A script reads, watches and listens to a query through DOMQL directly, with no managed bridge and no callback reference: ```js -const query = Domql - .from(viewport) - .select(view => ({ width: view.size.width, hasFocus: view.focus.within })); +const viewportQuery = domql.query('viewport { width = it.layoutSize?.inline, hasFocus = it.focusWithin }', { viewport }); + +const snapshot = await viewportQuery.evaluateAsync(); +const watch = viewportQuery.watch({ signal }); -const snapshot = await watcher.read(query); -const watch = await watcher.watch(query, snapshot => update(snapshot)); +watch.subscribe("change", (sender, args) => update(args.value), { signal }); ``` `WatchAsync` registers its handler before browser establishment begins, and the handler reads its immutable snapshot, so it works before the field receiving the watch is assigned. A watch has a nullable `Current`, `IsActive`, `IsDisposed`, `SyncAsync`, `RefreshAsync` and `DisposeAsync`. `IsActive` means an established watch with an accepted first snapshot. `Current` is the last accepted snapshot, so a snapshot whose answer is null is distinct from a `Current` of null; it is absent before establishment and is cleared on disabling, retargeting or known loss of reporting. A watch lasts until its owner disables or disposes it, or until a lifetime anchor the owner names leaves the document. An element the query reads leaving the document changes the snapshot, as DOMQL defines, and the watch runs on. These are local facts; they make no synchronous claim about the connection's health. -`SyncAsync` records the latest desired query and whether it should run, and behaviors follow the same pattern. Call and await it after each relevant render, with the current targets. The registration handles overlapping calls and reconciles the latest request; the component needs no synchronization guard. Disabling releases native resources, and enabling again delivers a fresh first snapshot. A watch's options belong to the watch call, `{ allowPartialObservation: true }` in JavaScript and `DomWatchOptions` in C#, and carry its schedule and whether it accepts partial observation, which a query over a partly observable fact requires, as DOMQL defines. An unavailable establishment leaves the watch inactive and retryable on the next synchronization; invalid requests and unexpected failures are surfaced. +`SyncAsync` records the latest desired query and whether it should run, and behaviors follow the same pattern. Call and await it after each relevant render, with the current targets. The registration handles overlapping calls and reconciles the latest request; the component needs no synchronization guard. Disabling releases native resources, and enabling again delivers a fresh first snapshot. A watch's options belong to the watch call, `{ acceptPartialObservation: true }` in JavaScript and `DomWatchOptions` in C#, and carry its schedule and whether it accepts partial observation, which a query over a partly observable fact requires, as DOMQL defines. An unavailable establishment leaves the watch inactive and retryable on the next synchronization; invalid requests and unexpected failures are surfaced. ### Occurrences @@ -230,21 +228,23 @@ Autofill is observed through CSS autofill animations, as a named browser adapter Where several consumers observe the same thing, sharing is keyed by the actual target, capability and normalized options, so different intersection roots or thresholds stay separate requests. Observer pools share compatible browser primitives while keeping each subscription distinct. A resize observer can cover several targets with target-specific options; an intersection observer shares only compatible roots, margins and thresholds. Mutation observation uses the coverage its source needs. Event listeners delegate only where the event's phase, bubbling and cancellation semantics permit it. -The browser watcher keeps document-level infrastructure only while subscribers need it. Native elements may be indexed internally with a `WeakMap`, and active subscriptions are explicitly reference-counted. Live registrations, listeners and callback references are still released by disposal. +DOMQL keeps document-level infrastructure only while subscribers need it. Native elements may be indexed internally with a `WeakMap`, and active subscriptions are explicitly reference-counted. Live registrations, listeners and callback references are still released by disposal. ## Crossing between C# and the browser A managed-to-browser invocation on Blazor Server normally waits for a network response. Browser-to-managed notifications and module fetches are counted separately, so optimizing one does not hide the cost of another. -- **One cached import per used root and runtime scope.** The bridge shares the successful import and any in-flight import for each root. Watcher use imports only the `DomWatcher.js` root, which loads DOMQL in the browser; the first action also imports `DomEngine.js`. The scope is a circuit on Server and the client application's service lifetime on WebAssembly. Browser-local capability imports are separate network fetches, not additional managed interop invocations. -- **Create and attach together.** Once its required root is imported, a registration call creates the owner's browser session if needed and attaches that registration. Subsequent registrations reuse it. Concurrent first requests share session creation, and a standalone action or read can create the session on first use as well. Required input-policy configuration remains visible in the crossing count. -- **The first snapshot in the result.** A read is one invocation returning its snapshot. A watch's establishment returns its first snapshot with the attach result, and the managed side delivers the first notification from it, with the ordering barrier described below, saving a separate initial callback. -- **No call for an unchanged, applied request.** `SyncAsync` compares target and options against successfully applied state. An equal request still retries inactive or known-invalid state. `RefreshAsync` explicitly requests a browser read and restores suspended reporting even when options are equal; local equality cannot prove browser health. +- **One connection per runtime scope.** DOMQL.NET's connection opens as its first request crosses, importing its browser module, which loads DOMQL. The scope is a circuit on Server, the client application's service lifetime on WebAssembly and a web view's in Blazor Hybrid. Loading a Forma module is a separate network fetch, asked for through the same connection before the first query that imports it. +- **One call per turn.** Every request a turn of the renderer makes crosses in one call as the turn ends: the watches, subscriptions and executions it starts, and the module loads they need. Required input-policy configuration remains visible in the crossing count. +- **The first snapshot in the answer.** A read is one invocation returning its snapshot. A watch's request answers with its first snapshot, which the watcher delivers as its first notification, saving a separate initial callback. +- **One call for each browser task's deliveries.** A watch's changes, a subscription's events and late answers that arise in one browser task cross together. +- **No call for an unchanged, applied request.** `SyncAsync` compares target and options against successfully applied state. An equal request still retries inactive or known-invalid state. `RefreshAsync` explicitly requests a browser read even when options are equal; local equality cannot prove browser health. - **One snapshot per query.** The facts a component needs together travel together, as one query's snapshot. +- **Large values within any message limit.** A batch of deliveries, and a request's answers, cross as data within DOMQL.NET's 16 KB budget and as a stream beyond it, which Blazor sends in chunks under any limit. - **Local interaction.** Input routes, gestures, panning, wheel movement, button-requested actions such as a scroll step, and placement run in the browser, and C# hears only the outcomes it requested. A local action makes no round trip of its own; a state change it causes still reaches C# as a notification. -- **One owner-resource release in ordinary teardown.** Context teardown marks all registrations disposed locally, then makes one browser call to release the owner's resources, engine before watcher. It uses this aggregate path rather than calling each child's public disposal method. An individual registration or borrowed engine still supports independent release. Compensating releases for late setup results and framework object-reference disposal calls are counted separately; correctness takes precedence over the ordinary-path call count. +- **One request in ordinary teardown.** Disposing a component's owner ends every watch, subscription and execution it started, in one request. An individual watch, subscription or behavior still supports independent release. -Private registration tokens identify browser-owned objects under the owner session; a separate managed JavaScript object reference per registration is unnecessary. The bridge's dispatch surface remains private and finite, and the public API remains typed requests. +DOMQL.NET's handles identify browser-owned objects under the owner; a managed JavaScript object reference per registration is unnecessary. Its dispatch surface remains private and finite, and the public API remains typed requests. Interop crossings are counted per scenario by the opt-in diagnostics. Counts distinguish cold initialization, warmed-root registration, input-policy setup, ordinary synchronization, notifications and teardown. @@ -252,15 +252,11 @@ Interop crossings are counted per scenario by the opt-in diagnostics. Counts dis ### Initial state and ordering -After capability loading, establishment installs listeners and evaluates the query for its baseline, waiting for its maintained facts' first samples as a DOMQL read does. The managed observation exists before that work starts. The managed side mints the registration's token and generation before the call and passes them with the attach request; the browser stamps every sample with them, and the attach result returns the baseline under the same identity. The managed receiver holds any early sample behind an establishment barrier, retaining only the latest pending state until that result is accepted. It installs `Current` and queues the initial notification before releasing later samples. A late result for an obsolete generation is discarded and its browser registration released. - -The browser attach path never awaits a managed notification, and the barrier opens before application handlers run. Establishment completes once the baseline is accepted, independently of callback completion. A failed establishment cancels its barrier, completes any delivery it was holding as discarded, so the browser's in-flight slot is free for a retry, and clears pending samples. This orders the returned baseline and asynchronous callbacks without a separate acknowledgement call. +After capability loading, establishment evaluates the query for its baseline, waiting for its maintained facts' first samples as a DOMQL read does. The managed watch exists before that work starts, so its handler is in place before the first snapshot. The watch's request answers with the baseline, or answers pending and delivers it whole once its maintained facts have arrived. A delivery that overtakes the answer waits for it, so `Current` is the baseline before any later change applies. Establishment completes once the baseline is accepted, independently of callback completion. -The browser sends a registration's first sample no sooner than a task after its attach returns, folding anything measured meanwhile into one latest sample. That makes an early sample rare on Blazor Server, but the barrier does not depend on it: a failed attachment, a disposal and an obsolete generation each release any delivery the barrier holds, without deadlock. +Each watch, subscription and behavior is a DOMQL.NET handle with a generation. Retargeting or updating it starts a new generation, and what an earlier one delivered is dropped. A handle disposed before its request is answered ends in the browser too. -Each registration has an internal identifier and a configuration generation. Replacing or disabling a target invalidates the previous generation immediately, and messages from obsolete generations are rejected. Delivery within a generation is serialized; a sequence number is added only where the transport needs one to enforce that order, and stays private. - -Separate watches and subscriptions carry no global order. Facts that must agree belong to one query, and an occurrence carries the snapshot it needs. +DOMQL.NET takes deliveries in the order they cross, across every handle of the connection, and none waits for a handler to complete. So a handler finds every delivery before its event applied, and none after it, until it first awaits. A watch that waits for its acknowledgment joins the changes that arise while one is in flight, so facts that must agree belong to one query, and an occurrence carries the snapshot it needs. Focus's watch waits for no acknowledgment, as the section on delivery sets out. ### Timing each capability preserves @@ -275,13 +271,15 @@ These are constraints on each capability's implementation. Invalidation, evaluat ### Bounded delivery and visible failure -The owner has one managed callback reference and one typed receiver, shared by watcher and engine notifications. Subscriptions dispatch independently, and no lock is held across application code. +The connection has one receiver for its runtime, which hands each delivery to the handle it names. Subscriptions dispatch independently, and no lock is held across application code. + +Every watch but focus's waits for its acknowledgment: it keeps one change in flight and joins those that arise meanwhile into one change set, with the first snapshot a complete baseline; after the baseline, a notification carries only what changed. DOMQL.NET applies a change set to the watch's copy before it acknowledges the batch, and calls the watch's handler after, one call at a time, with the latest snapshot. So a slow handler never holds the next change, and never sees a copy partly applied. A change set that doesn't apply leaves the copy uncertain, and the watch asks for its snapshot whole, skipping change sets until it arrives. -Focus is the exception: a press or a key acts on where the focus went, so its watch sends every state in the order it is measured, each as it is queued, as occurrences are sent. Every other watch keeps one delivery in flight and its pending changes coalesced into one change set, computed against the state the delivery in flight establishes once accepted, with the first snapshot protected as a complete baseline; after the baseline, a notification carries only what changed, through the same channel. Recovery follows DOMQL's ordering: once a fresh baseline is accepted, an abandoned delivery and its late completion change neither the state nor the delivery slot, which the registration's generation, or a private delivery revision beside it, enforces; the envelope carrying them is the implementation's. The interop invocation can stay outstanding until that watch's handler work completes; establishment, actions and unrelated subscriptions proceed meanwhile. Several listeners on one watch are awaited deliberately, each failure isolated and logged. +Focus is the exception: a press or a key acts on where the focus went, so focus's watch evaluates under the `immediate` schedule and waits for no acknowledgment. Each of its changes crosses with the browser task it happened in, in order with the events after it, so a handler acting on an event reads the focus as it stood when the event happened. -A rejected application handler is reported with the owner, capability and registration identity. A transport failure is reported locally in the browser and suspends managed delivery; bounded state is retained, and delivery resumes through explicit resynchronization. Every failure is reported: a shared helper never swallows a rejection the way `.catch(() => {})` does, and failure reporting never runs through the channel that failed. +A handler's failure, and every failure an operation reports, reaches the handle's failure handler, which the watcher and the engine report with the owner, capability and registration identity. A batch that can't be read leaves every copy uncertain until a refresh brings its snapshot whole. Every failure is reported: a shared helper never swallows a rejection the way `.catch(() => {})` does, and failure reporting never runs through the channel that failed. -Occurrences are delivered through a bounded ordered queue per consumer, with an explicit failure on overflow, and are never coalesced into state. The queue sends each occurrence as it is queued, never once .NET has acknowledged the one before it, since a click the browser dispatches next reaches .NET by Blazor's own route and would overtake a blur's flush held behind an earlier one. An action that must see what an occurrence carries waits for it to be applied, as the [edit boundary](browser-transfer-design.md#the-edit-boundary) does. Ordering applies while delivery is healthy; an occurrence whose delivery becomes uncertain on disconnection is not automatically replayed. State recovery uses a new snapshot, while occurrence recovery follows the capability's contract. +Occurrences are delivered in order and never coalesced into state. Each event crosses with its browser task, never once .NET has acknowledged the one before it, since a click the browser dispatches next reaches .NET by Blazor's own route and would overtake a blur's flush held behind an earlier one. Each handler starts as its event is taken, whatever handler before it still awaits, and its event is acknowledged once it completes. A host that leaves 4,096 deliveries unacknowledged has its connection closed, an explicit failure rather than an unbounded queue. An action that must see what an occurrence carries waits for it to be applied, as the [edit boundary](browser-transfer-design.md#the-edit-boundary) does. Ordering applies while delivery is healthy; an occurrence whose delivery becomes uncertain on disconnection is not automatically replayed. State recovery uses a new snapshot, while occurrence recovery follows the capability's contract. ### Actions and snapshots @@ -372,19 +370,19 @@ Focus's within fact reports whether the reader is within a surface. Focus inside ### Ownership -An owner has one watcher and an optional engine, sharing target identity, diagnostics and notification transport. The engine borrows the watcher: disposing the engine leaves the watcher, and disposing the watcher first ends dependent engine use. Each lifetime belongs to whoever created the object. +An owner has one watcher and an optional engine, sharing target identity, diagnostics and one `DomqlOwner`. The engine borrows the watcher: disposing the engine leaves the watcher, and disposing the watcher first ends dependent engine use. Each lifetime belongs to whoever created the object. -The bridge, `DomBridge`, is registered with `TryAddScoped` through the browser interop registrar. Its lifetime follows the interactive `IJSRuntime`: a circuit on Server and the application's service scope on WebAssembly, as described by [Blazor dependency injection](https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection). Each root has its own lazy import; an owner borrows those imports and owns its own session, callbacks, runtime identity and diagnostics. Sharing imports does not retain the first component's environment or logger as the identity of every subsequent owner. +DOMQL.NET's connection is registered through `AddDomql`, which the browser interop registrar calls, so a host that registered its own first still wins. Its lifetime follows the interactive `IJSRuntime`: a circuit on Server, the application's service scope on WebAssembly and a web view's in Blazor Hybrid, as described by [Blazor dependency injection](https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection). A component's owner is the connection's `DomqlOwner`, named by the component's runtime identity, and owns its handles; its diagnostics stay the component's own. -Prerendering creates no browser session and performs no import. Concurrent requests share an in-flight import. A rejected managed import attempt is cleared for a later explicit retry; unexpected module evaluation failures remain visible and are not retried in a loop. Disposing the bridge prevents new imports and releases any reference arriving from a late import. Owners never dispose shared module references. Application-resolved watchers use the registered bridge. Directly constructed watchers own a private bridge; only the registered construction path promises import reuse between owners. +Prerendering makes no request, so the connection doesn't open. Requests made while it opens cross with its first batch. Owners never dispose the connection. The connection, its owners and the components using them share one interactive runtime scope; process-wide state never captures a Server circuit's `IJSRuntime`. Independent use constructs a watcher from an `IJSEnvironment` and a connection; the caller owns it and any engine it creates. -Targets are cheap managed views. Watches, subscriptions and behaviors own resource leases and release them independently. Private identifiers are tokens, never HTML ids. The bridge and its owners use the same interactive runtime scope; process-wide state never captures a Server circuit's `IJSRuntime`. Independent use constructs a watcher from an `IJSEnvironment`; the caller owns it and any engine it creates. +Targets are cheap managed views. Watches, subscriptions and behaviors own resource leases and release them independently. Private identifiers are DOMQL.NET's handles, never HTML ids. ### Component context -`IComponentContext` exposes lazy `DomWatcher` and `DomEngine` properties. `ComponentContext` owns the objects it creates, using its existing JavaScript environment, runtime identity and logger. Constructing the engine configures no input; routed capabilities resolve the existing input collaborator when they first need it. +`IComponentContext` exposes lazy `DomWatcher` and `DomEngine` properties. `ComponentContext` owns the objects it creates, using its existing JavaScript environment, runtime identity and logger, and creates the component's `DomqlOwner` with the first of them. Constructing the engine configures no input; routed capabilities resolve the existing input collaborator when they first need it. -`FormaComponentBase.DisposeAsync` runs derived cleanup, then disposes an already-created context in a `finally` block, creating no context during teardown. Cleanup is idempotent, attempts every owned release even when one fails, and creates nothing after disposal. The context uses the aggregate owner-resource release: engine resources are released before watcher resources within that call. Late setup results are invalidated and released as they arrive. Shared imports remain owned by the bridge. +`FormaComponentBase.DisposeAsync` runs derived cleanup, then disposes an already-created context in a `finally` block, creating no context during teardown. Cleanup is idempotent, attempts every owned release even when one fails, and creates nothing after disposal. The context disposes its owner, which ends every watch, subscription and execution the component started in one request. Late setup results are invalidated and released as they arrive. The connection outlives every component's owner. ### Synchronization and racing renders @@ -394,7 +392,7 @@ A request arriving during an interop call remains pending. A late attachment mad Configuration is latest-wins; actions are each kept. Two explicit dispatches or downloads remain two requests, invocation order within a capability is preserved, and asynchronous completion is documented separately. Cancellation or supersession happens only where a method's contract defines it. -Generation invalidation guards every registration, because setup, parameter changes and disposal race. It is a private guard. Disposal invalidates queued work immediately, and a disposed registration never comes back. +Generation invalidation guards every registration, because setup, parameter changes and disposal race: DOMQL.NET drops what an earlier generation of a handle delivered. Disposal invalidates queued work immediately, and a disposed registration never comes back. ### Cleanup and reconnection @@ -402,9 +400,9 @@ Registrations release their listeners, observers, scheduled frames, gestures, te A document or browser-window subscription is released by explicit owner disposal, since no element removal marks its owner's end. A cleanup anchor beyond that is an explicit lifetime option. DOM cleanup cannot detect every disconnected or abandoned circuit. -A failed transport suspends reporting with bounded pending state. A connection interruption alone leaves the current page's JavaScript objects in place ([Blazor SignalR and reconnection](https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr)): a resumed circuit refreshes the same registrations, and a new circuit creates new component owners. On Server, when a circuit's connection is restored, its bridge asks the browser in one call to measure afresh and deliver anew each established observation of the sessions that reached the browser through it, naming each by owner, token and current generation. A state delivered while the connection was down is replaced by a complete baseline, even where the new measurement equals it, and a released or replaced registration is not revived. The hook belongs to the Server integration, and the bridge keeps the sessions and the refresh. The hook starts the refresh and never awaits the browser: a circuit handles one invocation from the browser at a time, so a reply awaited while the connection is coming up would queue behind the very invocation awaiting it. A watcher with a bridge of its own recovers through `RefreshAsync`. Non-idempotent actions are never repeated on reconnect. +A batch that can't be read leaves every watch's copy uncertain until a refresh brings its snapshot whole. A connection interruption alone leaves the current page's JavaScript objects in place ([Blazor SignalR and reconnection](https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr)): a resumed circuit refreshes the same watches, and a new circuit creates new component owners. On Server, when a circuit's connection is restored, the Server integration's hook starts the connection's `RefreshAsync`, which has every watch the connection established deliver its snapshot whole in one request. A state delivered while the connection was down is replaced by a complete baseline, even where the new measurement equals it, and a released or replaced watch is not revived. The hook starts the refresh and never awaits the browser: a circuit handles one invocation from the browser at a time, so a reply awaited while the connection is coming up would queue behind the very invocation awaiting it. A watcher on a connection of its own recovers through `RefreshAsync`. Non-idempotent actions are never repeated on reconnect. -Disposal from inside a notification invalidates the registration immediately and schedules the remaining release after dispatch unwinds, never awaiting the notification's own completion. Native handlers are removed before callback references are released. Managed release is best-effort when the transport is unavailable; local target cleanup remains effective. +Disposal from inside a notification invalidates the registration immediately and schedules the remaining release after dispatch unwinds, never awaiting the notification's own completion. A handle whose connection is gone has ended already; local target cleanup remains effective. ## Action outcomes and freshness @@ -432,13 +430,13 @@ Observers read after the DOM changes, and engine writes invalidate the observati ## Implementation boundaries -The API builds on `IJSEnvironment` and `JSModule`, adding a focused object-reference invocation helper where the roots need one, beside the existing `JSInterop` wrappers. The managed receiver dispatches private typed messages, and public callers make typed requests, so a component declares no `[JSInvokable]` method and holds no callback reference. +The API builds on DOMQL.NET, beside the existing `JSInterop` wrappers. DOMQL.NET's receiver dispatches every delivery, and public callers make typed requests, so a component declares no `[JSInvokable]` method and holds no callback reference. Browser.Interop's shared code keeps its foundation at the root and gives each capability area a folder of its own, with matching managed and browser implementation areas. A folder exists for an area a reader recognizes, never for a mechanism the root's types share: | Area | Contents | | --- | --- | -| Root | `DomWatcher`, `DomEngine`, targets, queries, snapshots and occurrence subscriptions, the registrations, sessions and delivery they share, and the clipboard, downloads, printing and sharing | +| Root | `DomWatcher`, `DomEngine`, targets, queries, snapshots and occurrence subscriptions, the owner and registrations they share, Forma's modules' loaders, and the clipboard, downloads, printing and sharing | | Input | Input routes and the occurrences they offer, over the input router | | Scrolling | Scroll state, intersection with a root and margin, frozen geometry, stepping, wheel movement and panning | | Virtualization | The virtualizer's measurement, rendered range and scrolling contract | @@ -458,20 +456,20 @@ Browser.Interop's shared code keeps its foundation at the root and gives each ca This organization governs all of Browser.Interop; the rest of the repository keeps the scripting guide's behavior, operation, component and service taxonomy. -The abstractions a caller names hold no script and live apart from it, in `Forma.Framework.Browser`, one namespace whatever their area: the observation interfaces and `IDomObservation`, the options and states the watcher and the engine take and report, the registrations a session holds and the entries they are made through, and the native operations a host stands in with. Browser.Interop implements them. +The abstractions a caller names hold no script and live apart from it, in `Forma.Framework.Browser`, one namespace whatever their area: the observation interfaces and `IDomObservation`, the options and states the watcher and the engine take and report, the registrations an owner holds and the entries they are made through, and the native operations a host stands in with. Browser.Interop implements them. ### Module structure -The composer's rich-text editor is the model. Its entry class composes concept classes, each in a module of its own, each taking its collaborators once in its constructor and keeping its mechanics `#private`, with listeners grouped under an `AbortController` for each owning lifetime. Observers, frames and other resources retain their own explicit cleanup. The watcher and the engine are built the same way: +The composer's rich-text editor is the model. Its entry class composes concept classes, each in a module of its own, each taking its collaborators once in its constructor and keeping its mechanics `#private`, with listeners grouped under an `AbortController` for each owning lifetime. Observers, frames and other resources retain their own explicit cleanup. Forma's DOMQL modules are built the same way: -- `DomWatcher.js` and `DomEngine.js` are the entries. Each composes its concept classes and holds no capability's mechanics of its own. +- Each module's entry declares what it offers DOMQL and composes its concept classes, holding no capability's mechanics of its own. - Each concern folder holds one concept per module, as a class: a scroll container, the observer of its state, the buttons that step it. A calculation belongs to the concept whose state it reads, as a member, rather than to a class of its own; the class boundary follows responsibility rather than the count of API methods. - What one document needs once, such as the measure-then-write frame scheduler, the shared native observer pools and the delegated document listeners, is a small service module with module-level state, installed on first use and removed with its last user. -- The watcher's entry statically imports its observation core and keeps optional observation concerns lazy. The engine loads a concern's modules with a dynamic `import()` when its first action or behavior needs them, and awaits them before installing any synchronous handler. Getting a managed capability property remains local. -- Imports stay shallow and are declared statically within a loaded concern where they are always needed. The entry does not eagerly import every observation concern: observation modules are also loaded on first use. Shallow dependency graphs limit discovery delays. +- Each module is loaded on request, through the loader Forma registers for it with DOMQL, once a query imports it, and a module's classes are in place before it installs any synchronous handler. Getting a managed capability property remains local. +- Imports stay shallow and are declared statically within a loaded module where they are always needed. Nothing imports every module eagerly. Shallow dependency graphs limit discovery delays. The input router shows both sides. What it does well carries over: document listeners installed on the first registration and removed after the last, decisions made in the browser with no crossing, and constant tables naming its rules. Its single file, holding binding matching, native-control claims, scopes, ambient dismissal and click suppression together, is the shape these modules avoid. -Behavioral concepts are testable through their constructor's collaborators; script tests cover their contracts, and integration tests cover composition. Every module is a `.js` file, which every host's file server serves with a JavaScript MIME type from the published static assets, MAUI's on Windows among them, which serves a `.mjs` file as a download. The input router's and the virtualizer's browser implementations keep their algorithms, and their component-facing contracts sit behind the engine and the watcher. Product-owned editor and data-view scripts keep their ownership, and third-party embedding adapters stay outside the generic DOM contracts in the Integrations area. Browser.Interop can depend on Input.Interop and never the reverse, and the watcher's JavaScript import graph excludes the input and engine modules. +Behavioral concepts are testable through their constructor's collaborators; script tests cover their contracts, and integration tests cover composition. Every module is a `.js` file, which every host's file server serves with a JavaScript MIME type from the published static assets, MAUI's on Windows among them, which serves a `.mjs` file as a download. The input router's and the virtualizer's browser implementations keep their algorithms, and their component-facing contracts sit behind the engine and the watcher. Product-owned editor and data-view scripts keep their ownership, and third-party embedding adapters stay outside the generic DOM contracts in the Integrations area. Browser.Interop can depend on Input.Interop and never the reverse, and a query that imports no input module loads none. Diagnostics identify the owner's `RuntimeId`, the capability, the registration generation and the operation. Small opt-in counters measure registrations, notifications and crossings, and record no text, clipboard or file contents. diff --git a/docs/dom-watcher-engine-implementation-plan.md b/docs/dom-watcher-engine-implementation-plan.md index bd442889..288b26a3 100644 --- a/docs/dom-watcher-engine-implementation-plan.md +++ b/docs/dom-watcher-engine-implementation-plan.md @@ -34,8 +34,8 @@ Each step is independently reviewable. The context-lifetime change stands alone; - The focus observation takes options with no members, so it keeps the shape every observation shares. Breaking changes, while unreleased: the `Focus` behavior was removed, `FocusOrientation` moved to the focus area, and `FormaDateTimePicker.HandleFocusLeaveAsync` was removed. -5. **The request model.** Open. The public model the design's opening sets out: queries read once or watched, snapshots, occurrence subscriptions with their ordering and capacity, actions and behaviors. One slice proves it with all four: `FormaFreezePane` and `FormaDateTimePicker` read and watch scroll and focus facts through queries, the toolbar's roving is a behavior, and one input-routing consumer establishes its routes through the engine and receives its actions as occurrences. The slice settles whether C# checks the type a snapshot maps onto before the first snapshot or at it, how a watch's query takes the targets of a new render, and the occurrence queue's capacity, overflow failure and disconnection limits. DOMQL takes a repository and a package of its own, `formaui-net.DOMQL` in the sibling Forma.DOMQL repository, as the design's section on it sets out, referenced by the input and browser interop assemblies and referencing neither. The scroll, intersection and focus capabilities then move onto the model, and their per-capability observation and interaction API is retired; an intersection's first state comes from the browser's intersection observation, as DOMQL's `intersects` defines, rather than from comparing boxes, and whether an element is attached is observed through the document's structure while a watch reads it, with that observation's cost measured. Gate: an unavailable fact distinct from zero or false; `@table.all("tbody tr").max(rect.height)` following rows added and removed, a row's height changing, an empty table and the watch's disposal while its dependencies change; an element leaving and returning to the document changing the snapshot while the watch runs on; a watch over a partly observable member refused unless it accepts partial observation, and a missed change reaching an accepting watch through a refresh; a maintained observation released when its read succeeds, fails or is canceled and when a watch stops depending on it, and a borrowed one left running for its other holders; a first answer delivered only once no fact it reads is pending, its wait cancelable and ended by a member reporting itself unavailable; an occurrence's shape evaluated as the source delivers it, with only its answer queued; a failed evaluation reported, retried and recovered; a script reading, watching and listening with no managed bridge; a read making one crossing; a watch delivering a complete baseline and then change sets carrying only what changed, a field set to null distinct from one left out, list items added, removed and moved by element, pending changes coalesced against the receiver's baseline, a fresh baseline after a failed delivery, reconnection or retargeting, and a delivered snapshot never changing; an old delivery held through a recovery, then released with its completion, leaving state and delivery bookkeeping where the recovery put them; a failed change set exposing no partial answer, and a failing handler neither undoing nor replaying an accepted one; an occurrence's maintained member null on the first occurrence and read from its sample on a later one, and a subscription releasing the leases its shapes no longer read, cleaning up after a failed evaluation and on disposal, and leaving an observation another holder leases running; occurrences kept in order and never coalesced; `formaui-net.DOMQL` referencing neither interop assembly and its contracts naming no concrete watcher, engine or transport type; using the router alone loading no DOMQL module; a request loading only the capabilities it names, an observation naming no input loading no input integration, observation establishing no routing behavior, and the watcher's import graph free of the engine; `Domql.registerModule` keeping one registry of definitions per document, with instances, subscriptions and owner state scoped apart and a released instance leaving its module registered; and no component-facing interop wrapper or callback reference left for a converted capability. - DOMQL's language core is built in the sibling DOMQL repository, which holds its specification, its design and its tests. Still open within the step: the first project here referencing `Forma.DOMQL` by path, with the build and continuous integration checking the sibling repository out beside this one; the watcher's reads, watches and subscriptions over DOMQL's queries, the C# half and the conversions. +5. **The request model.** Open. The public model the design's opening sets out: queries read once or watched, snapshots, occurrence subscriptions with their ordering and capacity, actions and behaviors. One slice proves it with all four: `FormaFreezePane` and `FormaDateTimePicker` read and watch scroll and focus facts through queries, the toolbar's roving is a behavior, and one input-routing consumer establishes its routes through the engine and receives its actions as occurrences. The slice settles whether C# checks the type a snapshot maps onto before the first snapshot or at it, which serializer options make each mapping failure the design lists one, and how a watch's query takes the targets of a new render. DOMQL takes a repository and a package of its own, `formaui-net.DOMQL` in the sibling Forma.DOMQL repository, as the design's section on it sets out, referenced by the input interop assembly and referencing neither. DOMQL.NET, DOMQL's own .NET host, takes the sibling DOMQL.NET repository and its package `formaui-net.DOMQL.NET`, which the browser interop assembly references, and carries every request, snapshot and occurrence between C# and the browser; Forma's host layer over it is what [replacing Forma's JavaScript with DOMQL](forma-javascripts-domql-replacement.md) names in F1. The scroll, intersection and focus capabilities then move onto the model, and their per-capability observation and interaction API is retired; an intersection's first state comes from the browser's intersection observation, as DOMQL's `intersects` defines, rather than from comparing boxes, and whether an element is attached is observed through the document's structure while a watch reads it, with that observation's cost measured. Gate: an unavailable fact distinct from zero or false; `@table.all("tbody tr").max(rect.height)` following rows added and removed, a row's height changing, an empty table and the watch's disposal while its dependencies change; an element leaving and returning to the document changing the snapshot while the watch runs on; a watch over a partly observable member refused unless it accepts partial observation, and a missed change reaching an accepting watch through a refresh; a maintained observation released when its read succeeds, fails or is canceled and when a watch stops depending on it, and a borrowed one left running for its other holders; a first answer delivered only once no fact it reads is pending, its wait cancelable and ended by a member reporting itself unavailable; an occurrence's shape evaluated as the source delivers it, with only its answer queued; a failed evaluation reported, retried and recovered; a script reading, watching and listening with no managed bridge; a read making one crossing; a watch delivering a complete baseline and then change sets carrying only what changed, a field set to null distinct from one left out, list items added, removed and moved by element, pending changes coalesced against the receiver's baseline, a fresh baseline after a failed delivery, reconnection or retargeting, and a delivered snapshot never changing; an old delivery held through a recovery, then released with its completion, leaving state and delivery bookkeeping where the recovery put them; a failed change set exposing no partial answer, and a failing handler neither undoing nor replaying an accepted one; an occurrence's maintained member null on the first occurrence and read from its sample on a later one, and a subscription releasing the leases its shapes no longer read, cleaning up after a failed evaluation and on disposal, and leaving an observation another holder leases running; occurrences kept in order and never coalesced; `formaui-net.DOMQL` referencing neither interop assembly and its contracts naming no concrete watcher, engine or transport type; using the router alone loading no DOMQL module; a request loading only the capabilities it names, an observation naming no input loading no input integration, observation establishing no routing behavior, and a watcher-only request loading no behavior's module; focus's every state reaching C# ahead of the press or the key that follows it, on Server and WebAssembly; a Server circuit's restored connection refreshing every watch without awaiting the browser; a watch's first snapshot and an execution's answer past Blazor Server's message limit arriving whole; `Domql.registerModule` keeping one registry of definitions per document, with instances, subscriptions and owner state scoped apart and a released instance leaving its module registered; and no component-facing interop wrapper or callback reference left for a converted capability. + DOMQL's language core is built in the sibling DOMQL repository, which holds its specification, its design and its tests. Still open within the step: DOMQL.NET's first release, with the four needs of Forma's it meets first, which [the order of the work](forma-javascripts-domql-replacement.md#the-order-of-the-work) lists; the browser interop assembly referencing `formaui-net.DOMQL.NET` once it is published; the watcher's reads, watches and subscriptions through each component's DOMQL.NET owner, and Forma's host layer over it; and the conversions. 6. **Input routing.** Open. `InputRouterDomqlModule` exposes the router's state, occurrences, actions and behaviors through DOMQL, with the router usable on its own as before. Components establish routes through the engine and receive the actions and dismissals they matched as occurrences through the watcher, and the input registration each component holds today, with its callback reference and `[JSInvokable]` handlers, is retired. The router's browser algorithms stay as the input router design states them. Gate: input ownership, native-control claims, scopes, remapping and dismissal unchanged, and the router's existing script tests passing. 7. **Anchored presentation.** Open. Anchored surfaces move onto placement and presentation objects composed with focus, with the invalidation coverage the design's observation and position section requires, and `FormaPopover` converts. Gate: placement under scrolling and resizing, focus returned to the trigger, Tab wrapping inside, host-style ownership, and the popover's update measured: - The same popover follows the same moving anchor twice, once with today's direct writes of `left` and `top` and once with its two owned writes. diff --git a/docs/features-status.md b/docs/features-status.md index df22f7c1..096ecbdb 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -150,7 +150,7 @@ check reaches through Safari's remote inspector. [Its plan](dom-watcher-engine-implementation-plan.md) has landed the component context's disposal, the watcher and engine, intersection and focus, steps 0 to 4, and of step 11 the autofill and size observations. Steps 5 to 11 move the rest of the browser work onto them: DOMQL as the language a component's queries are written in, the input router's participation, and each remaining behavior, operation and component script, retiring the kind folders as each empties. -DOMQL's language now lives in Nexo, which was ported out of DOMQL, and DOMQL has moved onto it in its own repository. The queries [the DOM watcher and engine design](dom-watcher-engine-design.md) writes as examples predate the notation DOMQL took with Nexo, which [replacing Forma's JavaScript with DOMQL](forma-javascripts-domql-replacement.md) writes, and are brought up to it with the design. +DOMQL's language now lives in Nexo, which was ported out of DOMQL, and DOMQL has moved onto it in its own repository. C# reaches DOMQL through [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), DOMQL's own .NET host, which carries every request, snapshot and occurrence between them; step 5 builds on its first release, once it meets the four needs of Forma's [the order of the work](forma-javascripts-domql-replacement.md#the-order-of-the-work) lists. The queries [the DOM watcher and engine design](dom-watcher-engine-design.md) writes as examples predate the notation DOMQL took with Nexo, which [replacing Forma's JavaScript with DOMQL](forma-javascripts-domql-replacement.md) writes, and are brought up to it with the design. diff --git a/docs/forma-javascripts-domql-replacement.md b/docs/forma-javascripts-domql-replacement.md index b8ecb683..18d5aed5 100644 --- a/docs/forma-javascripts-domql-replacement.md +++ b/docs/forma-javascripts-domql-replacement.md @@ -1,6 +1,6 @@ # Replacing Forma's JavaScript with DOMQL -At `592b12b7`, the Forma commit this survey reads, Forma's components did their browser work through 84 scripts, 10,792 lines of JavaScript. Each is to become DOMQL infrastructure: a query, a watch, a subscription, an execution, a Forma module's implementation, or Forma's host layer around DOMQL. This document records what that replacement needs of DOMQL, and what each script becomes. +At `592b12b7`, the Forma commit this survey reads, Forma's components did their browser work through 84 scripts, 10,792 lines of JavaScript. Each is to become DOMQL infrastructure: a query, a watch, a subscription, an execution, a Forma module's implementation, or part of [DOMQL.NET], DOMQL's own .NET host, under Forma's host layer over it. This document records what that replacement needs of DOMQL and DOMQL.NET, and what each script becomes. DOMQL's [planned capabilities](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md#planned-capabilities) give each capability an identifier, and name no consumer. Each is now implemented, or declined with an alternative, as DOMQL's [decisions](https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md) record. This document adds what those records leave to Forma: @@ -51,7 +51,7 @@ In this document: ## The verdict -DOMQL's model fits Forma, and nothing in DOMQL blocks Forma's plan any longer. +DOMQL's model fits Forma, and nothing in DOMQL blocks Forma's plan any longer. DOMQL.NET, through which Forma's C# reaches it, has four of Forma's needs to meet and its first release to make before step 5 builds on it. - **Every capability the survey asked of DOMQL is settled.** Each V, E, O, X, C, T and A item is implemented, or declined with an alternative Forma uses, by a decision of DOMQL's. [What Forma uses of DOMQL](#what-forma-uses-of-domql) gives each one's decision and the scripts that use it. - **The two gaps the recheck found are closed:** @@ -63,8 +63,8 @@ DOMQL's model fits Forma, and nothing in DOMQL blocks Forma's plan any longer. - the frame's placement results name their drag, and C# subscribes to them before the frame starts, since it reports as it starts; - a behavior whose options change binds them, since an update replaces bindings, never a text's literals; - a member reading maintained values is nullable (NEXO4071), and each C# record takes the null or the host passes on none. -- **The C# half waits for its design** ([D46]), and A5's bounded queue with it ([D69]). Forma's host layer covers both meanwhile. It carries each watch's snapshots, each behavior's occurrences and each execution's answer to C#, which DOMQL hands it in the order they happen, across handles and owners. -- **The reading half is done.** DOMQL serves these outright, through the host layer: +- **The C# half is DOMQL.NET** ([D119]), DOMQL's own host of its connection, in a repository and a package of its own, `formaui-net.DOMQL.NET`. It carries each watch's snapshots, each behavior's occurrences and each execution's answer to C#, taking them in the order they cross, across handles and owners. A watch that waits for no acknowledgment, as focus's does, crosses each change in order with the events after it ([D121]). Forma's host layer over it holds what is Forma's alone (F1). +- **The reading half is done.** DOMQL serves these outright, through DOMQL.NET: - the data cards' column count, `GridColumns.js`; - the explorer's header tier, `Breakpoint.js`; - the data view's height reservation, `HeightReservation.js`; @@ -75,7 +75,7 @@ DOMQL's model fits Forma, and nothing in DOMQL blocks Forma's plan any longer. Every observation Forma's foundation runs by hand, its frame coalescing, its change-only reporting and its detached elements, is what a DOMQL watch does already. Its resize and intersection pools are not: DOMQL keeps a native observer for each element, where the pools share one, which costs observers and changes no behavior. - **Forma's algorithms stay Forma's.** Under the [decisions](#decisions-the-replacement-rests-on) below, the input router, the gestures, placement, focus, the virtualizer and the rich-text editor become Forma modules' implementations, and the culture coordinator keeps its own bridge, outside DOMQL, since its registration precedes a circuit's first render ([culture](#culture)). Their listeners, reads and writes stay native, inside them. They reach DOMQL through its extension contract: occurrences, commands, the owner, a behavior's state, and owned writes beside Blazor's render. -- **What remains is Forma's work,** step by step, beginning with the host layer at step 5, as [the order of the work](#the-order-of-the-work) sets out. +- **What remains is DOMQL.NET's first release, then Forma's work,** step by step, beginning with the host layer at step 5, as [the order of the work](#the-order-of-the-work) sets out. ## How the scripts map onto DOMQL @@ -89,7 +89,7 @@ Each script becomes one of DOMQL's request kinds, or stays where it is. A script | A change C# asks for once: focus, scroll, copy, print | A once execution | `executeAsync` | 11 | | A behavior attached for a lifetime: routes, a gesture, a placement, an editor | A continuous execution | `run`, `update`, `dispose` | 19 | | An algorithm no request can express: input ownership, gestures, focus, rich-text editing, culture | A Forma module's implementation | Declared with `domql.createModule`, and loaded on request through a loader registered by its name ([D68]) | 24 | -| Transport, sessions, tokens and generations, one delivery in flight, reconnection | Forma's host layer around DOMQL | None: they are Forma's interop concerns | 12 | +| Transport, sessions, tokens and generations, one delivery in flight, reconnection | Retires into DOMQL.NET, and Forma's host layer over it | DOMQL.NET's connection, owners and handles ([D119], [D121]) | 12 | | A helper module code calls synchronously, or a pure transform | Stays as it is | None | 5 | Forma's design calls a once execution an **action**, a continuous one a **behavior**, and what a behavior's event source delivers an **occurrence**. DOMQL calls a once execution that reaches a running behavior a **command**. @@ -122,7 +122,7 @@ What Forma uses of DOMQL rests on these decisions. D1 to D3 are DOMQL's, recorde | D1 | Generic web-platform changes are DOMQL's built-in executions, and Forma's algorithms are Forma's modules. A change is built in where it is one platform call with a platform result, as focusing, scrolling, showing a popover and writing the clipboard are. It is a module's where it carries a policy, as stop-aware stepping, placement, gestures and roving focus do. | DOMQL | DOMQL stays independent of its consumers, and every consumer needs the generic half. | | D2 | `on` stays passive and never cancels. Canceling an event, consuming a key, claiming a click and capturing a pointer stay synchronous inside a module's own listeners: the input router's, and those of the modules that compose it. `on` listens in the capture phase too, for observing alone ([D27]). | DOMQL | Every input a component acts on is a route on the input router, so a canceling `on` would let a component act past it. A canceling subscription would also have to decide synchronously, before any caller sees the event. | | D3 | A behavior's occurrences are event sources of the module that declares the behavior. A source is bound to the running continuous execution of the same owner on the same receiver, and outlives its replacement and release ([D49]). | DOMQL | Forma's design states this contract, and every behavior that reports needs it. | -| F1 | Forma keeps its host layer: the transport to C#, sessions by runtime key, tokens and generations, a watch's state delivered one at a time with only the latest waiting, but focus's, every state of which is sent in order as it is measured, since a press or a key acts on where the focus went, occurrences sent in order as they happen and never held for an earlier one's acknowledgment or coalesced ([D69]), every value a reader can make large crossing through the [browser transfer](browser-transfer-design.md), suspension and resumption, and reconnection. While the C# half waits for its design ([D46]), the host layer carries every result to C#, and loads each Forma module through DOMQL's loader before a query that imports it ([D68]). | Forma | They are Forma's interop concerns, and DOMQL's `signal` already gives each owner its disposal. | +| F1 | Forma's C# reaches DOMQL through DOMQL.NET, and Forma's host layer over it holds what is Forma's alone: each component's `DomqlOwner`, named by its runtime key and ended with it, its handles' failures reaching the component's log; `DomWatcher` and `DomEngine`, making their typed requests through that owner and reconciling each with the latest render; focus's watch waiting for no acknowledgment, since a press or a key acts on where the focus went ([D121]); each Forma module's loader, registered with DOMQL and loaded before a query that imports it ([D68]); a Server circuit's restored connection starting DOMQL.NET's refresh of every watch; and the [edit boundary](browser-transfer-design.md#the-edit-boundary). | Forma | DOMQL's transport is the one its hosts use ([D119]). The transport, tokens and generations, the order of deliveries, every value a reader can make large crossing as a stream beyond the budget, and refreshing after a reconnection are DOMQL.NET's. A component's lifetime, Forma's modules, its Server integration and its forms are Forma's. | | F2 | The scripts Forma's modules call synchronously stay plain classes that work without DOMQL, composed inside the modules: `FocusSurface`, `TabOrder`, the drag gesture, `Controls`, `Direction`, `Scrolling` and `FrameScheduler`. | Forma | Their callers decide inside native handlers, where no query can run. | | F3 | A frame hands its geometry back to the render through a `commit` command carrying the placement Forma accepted and naming the drag its placement result reported, run from `OnAfterRenderAsync` of the render that carries it, for the frame's owner, never through DOMQL's acknowledgement ([D50]). A drag that starts while an earlier drag's hand-over is pending takes the holdings over, so the earlier `commit` releases nothing. The design's [frames](dom-watcher-engine-design.md#frames) state the rule. | Forma | A placement Forma rejects or keeps renders nothing. Ending the holdings would then leave the drag's geometry, and restoring would undo a placement Forma accepted. The acknowledgement carries no placement to settle either. | @@ -239,16 +239,16 @@ DOMQL's [extension contract](https://github.com/FormaUI/DOMQL/blob/main/docs/fea ### API and host -DOMQL's [API and host](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md#planned-api-and-host): A2 to A10, implemented or declined. A1, the C# half, and A5's queue wait for its design. +DOMQL's [API and host](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md#planned-api-and-host): A1 to A10, implemented or declined. A1, the C# half, is DOMQL.NET. | | Capability | Decision | Used by | Also | | --- | --- | --- | --- | --- | -| A1 | The C# half | Deferred until it is designed ([D46]). Forma's host layer carries every result to C# meanwhile (F1) | Every script with a C# wrapper, through the host layer | — | -| A2 | Change sets against an acknowledged result | Declined ([D65]): change sets compose, so a host concatenates the pending ones, or sends the latest snapshot whole as one root replace | `OwnerWatcher.js`, `StateDelivery.js`, once change sets cross | — | -| A3 | A refresh that takes new samples, `refreshAsync({ resample: true })`, its wait canceled by a `signal` | [D66]; `rebaseline` declined, since the host reads `watch.snapshot` once the refresh settles | `IntersectionStateObserver.js` and the pool it retires, `IntersectionObserverPool.js`: the explorer and the emoji picker refresh their sentinel after each load, sending C# the `snapshot` the refresh leaves. `DomWatcher.js`'s `refreshAll`, reading `snapshot` after a reconnection | — | -| A4 | Modules loaded on request, `domql.registerModuleLoader` and `domql.loadModulesAsync` | [D68]. Nothing loads a module implicitly: a request importing a module whose loader hasn't run yet is refused with `DOMQL3007` | Every Forma module, through the host layer: `DomWatcher.js`, `DomEngine.js` and `OwnerEngine.js` | — | -| A5 | Ordered occurrence delivery to C# | The JavaScript side ([D69]): what DOMQL delivers reaches its handlers in the order it happens, across handles and owners. The C# half's bounded queue waits with A1 ([D46]), and Forma's host layer keeps a queue of its own meanwhile, which sends each occurrence as it is queued. In a Blazor Web App of its own, a queue that sent each only once .NET had completed the one before let a button's click overtake an editor's flush on blur in every run, Server and WebAssembly | `InputRouter.js`, `DropZone.js`, `ReorderInteraction.js`, `Wheel.js`, `Splitter.js`, `SelectionInteraction.js`, `RichTextEditor.js`, `CultureCoordinator.js`; `Owner.js`'s reports | — | -| A6 | An execution's lifetime anchored to its element | Declined ([D74]): the caller watches `attached` and disposes the execution once it reads false | `DomElement.js`, `DomElements.js`, `OwnerEngine.js`: the host ends an execution through a watch of `it.attached` | — | +| A1 | The C# half | DOMQL.NET ([D119]): one connection for each browser runtime, owners, watches keeping a typed copy, subscriptions, executions, and each batch beyond the budget crossing as a stream | Every script with a C# wrapper, through Forma's host layer (F1) | — | +| A2 | Change sets against an acknowledged result | Declined ([D65]): change sets compose, so a host concatenates the pending ones, or sends the latest snapshot whole as one root replace. DOMQL's connection joins the changes that arise while one is unacknowledged ([D119]) | `OwnerWatcher.js` and `StateDelivery.js`, retiring into DOMQL.NET | — | +| A3 | A refresh that takes new samples, `refreshAsync({ resample: true })`, its wait canceled by a `signal` | [D66]; `rebaseline` declined, since the host reads `watch.snapshot` once the refresh settles. The connection's `refresh` delivers the snapshot whole, changed or not | `IntersectionStateObserver.js` and the pool it retires, `IntersectionObserverPool.js`: the explorer and the emoji picker refresh their sentinel with a new sample after each load, and C# receives the snapshot the refresh leaves. DOMQL.NET's refresh of every watch after a reconnection | — | +| A4 | Modules loaded on request, `domql.registerModuleLoader` and `domql.loadModulesAsync` | [D68]. Nothing loads a module implicitly: a request importing a module whose loader hasn't run yet is refused with `DOMQL3007`. The connection loads one through its `load` request | Every Forma module, through the loaders Forma's host layer registers and the loads it asks for before a query (F1) | — | +| A5 | Ordered occurrence delivery to C# | The JavaScript side ([D69]): what DOMQL delivers reaches its handlers in the order it happens, across handles and owners. DOMQL.NET takes each delivery in the order it crossed, an event never waiting for a watch's acknowledgment or a handler ([D119]), and a host that leaves 4,096 deliveries unacknowledged has its connection closed with `DOMQL5026`. In a Blazor Web App of its own, a queue that sent each only once .NET had completed the one before let a button's click overtake an editor's flush on blur in every run, Server and WebAssembly | `InputRouter.js`, `DropZone.js`, `ReorderInteraction.js`, `Wheel.js`, `Splitter.js`, `SelectionInteraction.js`, `RichTextEditor.js`, `CultureCoordinator.js`; `Owner.js`'s reports | — | +| A6 | An execution's lifetime anchored to its element | Declined ([D74]): the caller watches `attached` and disposes the execution once it reads false | `DomElement.js`, `DomElements.js`, `OwnerEngine.js`, retiring into Forma's host layer, which ends an execution through a watch of `it.attached` | — | | A7 | Reactions: once executions a subscription carries out inside each event's delivery, `event` bound, before its handler, so they keep the user's activation | [D71] | `Clipboard.js` and `Share.js`: the copy and the share inside the press that asks for them. `RichTextEditor.js`: its editor commands inside the key's dispatch, through a dictionary from the router's action to the editor's command, and a paste from a menu inside its press | `Dialog.js`'s scrim close, which a reaction doesn't fit, since it runs for every click its subscription hears. `TextEntry.js`'s selection after Go, which waits for C#'s render of the entry | | A8 | The element a watch's list item came from, `watch.sourceOf(...path)` | [D72] | — | `BlockAlignment.js` as a watch | | A9 | A delayed schedule, which a refresh flushes; reporting on parts; a subscription's throttle. Delivery by frame is declined, since a throttle paces events and what a frame renders reads the latest itself | [D73] | `InputInspector.js`: a throttle keeping the latest wheel decision, on a subscription to wheels of its own. `TextEntry.js`: the plain text editor's selection watched under a delay | — | @@ -286,12 +286,10 @@ DOMQL's [timing](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status ### Corrections to DOMQL's definitions -The survey found 23 of DOMQL's definitions incomplete or wrong: V5, V9, V17, E2, E9, O2, X2, X3, X5, X7, C1, C3, C5, C7, C8, C10, A1, A2, A3, A5, A7, A9 and A10. DOMQL adopted each but A1's, in the decision the tables above give for the item. +The survey found 23 of DOMQL's definitions incomplete or wrong: V5, V9, V17, E2, E9, O2, X2, X3, X5, X7, C1, C3, C5, C7, C8, C10, A1, A2, A3, A5, A7, A9 and A10. DOMQL adopted each in the decision the tables above give for the item, A1's in DOMQL.NET ([D119]): -A1's correction waits with the C# half, whose design takes it up ([D46]): - -- **A host that keeps its own transport** (F1) takes over delivery and recovery. The C# half's outline queues every change after the baseline and rebuilds from a fresh watch on uncertainty, while Forma delivers the latest state alone with one delivery in flight, sends occurrences in order and never coalesces them, and refreshes established watches on reconnection. So such a host uses the typed queries and records without the adapter's synchronization. -- **A result maps onto records** a field written first discriminates, as the router's `InputInfo` is by `family`. +- **One transport for every host.** The C# half's outline queued every change after the baseline and rebuilt from a fresh watch on uncertainty. DOMQL's connection, which DOMQL.NET hosts, sends a watch's change once the one before it is acknowledged, joining what arises meanwhile, or each change with its task where the watch waits for no acknowledgment ([D121]). It sends occurrences in order and never joins them, and DOMQL.NET refreshes every watch after a reconnection. So a host keeps no transport of its own. +- **A result maps onto records** a field written first discriminates, as the router's `InputInfo` is by `family`, through the serializer's polymorphism. #### Enhanced navigation @@ -304,11 +302,11 @@ Blazor's enhanced navigation merges the new page into the document in place, and #### The browser transfer and the edit boundary -Forma's [browser transfer](browser-transfer-design.md) carries every value a reader can make large from the browser to .NET, inline within a fixed budget and as a stream beyond it, and holds an action back until the edits before it are applied. It is the host layer's, so DOMQL changes nothing for it, and every converted script keeps it: +Forma's [browser transfer](browser-transfer-design.md) carries every value a reader can make large from the browser to .NET, inline within a fixed budget and as a stream beyond it, and holds an action back until the edits before it are applied. Under DOMQL, DOMQL.NET carries the values and Forma's host layer keeps the edit boundary, so every converted script keeps both: | Part | Under DOMQL | Rests on | | --- | --- | --- | -| The transfer | The host layer sends each snapshot, occurrence and answer DOMQL hands it through the transfer: the DOM watcher's states, the editor's activations, the data view's range of tokens, the menu's document order, a taken text and a composed print document | — | +| The transfer | DOMQL.NET carries each snapshot, occurrence and answer inline within its 16 KB budget and as a stream beyond it, a request's answers as well as each batch of deliveries: the DOM watcher's states, the editor's activations, the data view's range of tokens, the menu's document order, a taken text and a composed print document | [D119] | | A text field's edits | A behavior of `FormaText` on the field, delivering `{ revision, start, removed, inserted }` to a source as its own `input` listener computes each, and offering its revision as state a member reads. .NET's own change reaches the field through a command that writes it and moves the revision on. The browser holds the text, so Blazor renders no `value` into the field | Occurrences ([D49]), in order ([D69]), acknowledged ([D50]); state ([D52]); commands ([D48]) | | The edit boundary | At a participating press or submit, inside its dispatch, the host layer reads the revisions in the form and runs each field's flush command, which delivers its debounced edit at once. It then waits until C# has applied every edit through those revisions, which each occurrence's acknowledgment tells it, before the action is validated. A failed or refused edit stops the action | Commands within the call ([D48], [D64]); acknowledgment ([D50]) | | The order | Edits are sent as they happen, never held behind an earlier edit's acknowledgment nor coalesced, and C# applies them in revision order, so an edit that arrives late, behind a newer one, is dropped | [D69] | @@ -328,7 +326,7 @@ A Blazor Web App of its own showed why the boundary is needed, Server and WebAss Each row says who uses the script, what it becomes, what of DOMQL it rests on, and the step that converts it. Nothing a row rests on is missing from DOMQL: -- **The C# half** waits for its design (A1, [D46]), so Forma's host layer carries every snapshot, occurrence and execution answer to C#. +- **The C# half** is DOMQL.NET (A1, [D119]), which carries every snapshot, occurrence and execution answer to C#, under Forma's host layer (F1). - **Every Forma module** is loaded through the loader the host layer registers for it, before a query that imports it (A4, [D68]), so no row lists A4. Line counts are the script's at the baseline. Examples leave out the import of the Forma module they use, since an import takes a line of its own (NEXO1044). @@ -359,38 +357,40 @@ What they become, counted once each: | A once execution | 11 | `Scroll`, `Dialog`, `Asset`, `CheckBox`, `Clipboard`, `Download`, `Embedding`, `Playback`, `Print`, `Share`, `TextEntry` | | A continuous execution | 19 | `TextEdits`, `ScrollInteraction`, `FocusInteraction`, `AnchoredPopover`, `AutofillTracker`, `DropZone`, `FileDropZone`, `FilePreview`, `PanGesture`, `ReorderInteraction`, `Wheel`, `Frame`, `Splitter`, `Window`, `RichTextEditor`, `BlockAlignment`, `SelectionFollower`, `SelectionInteraction`, `ReadingPlace` | | A Forma module's implementation | 24 | `CharacterCount`, `TextSources`, `ScrollContainer`, `ScrollButtons`, `FocusSurface`, `TabOrder`, `RovingFocus`, `FocusRecovery`, `DragGesture`, `Pointer`, `CultureCoordinator`, `InputRouter`, and the twelve modules of the rich-text editor | -| Forma's host layer | 12 | The ten scripts of the foundation but its two pools, `Owner` and `Transfer` | +| Retires into DOMQL.NET, and Forma's host layer over it | 12 | The ten scripts of the foundation but its two pools, `Owner` and `Transfer` | | Stays as it is | 5 | `Controls`, `Direction`, `FrameScheduler`, `Sanitizer`, `Scrolling` | The culture initializer outside `scripts/` stays as it is too, which makes 85 files in all. ### The DOM watcher and engine foundation -`src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/`, the bridge between C# and the browser that steps 1 and 3 built. Most of it becomes Forma's host layer around DOMQL (F1). Its pools retire into DOMQL's own observations. Every row moves onto the request model at step 5. +`src/Framework/Forma.Framework.Browser.Interop/wwwroot/scripts/`, the bridge between C# and the browser that steps 1 and 3 built. Its transport, sessions, tokens, generations and delivery retire into DOMQL.NET, and what is Forma's alone moves into the host layer over it (F1). Its pools retire into DOMQL's own observations. Every row moves onto the request model at step 5. | Script | Lines | Used by | Becomes | Rests on | | --- | --- | --- | --- | --- | -| `DomWatcher.js` | 47 | C#'s `DomWatcher`: `FormaFreezePane`, `FormaExplorerContentArea`, `FormaEmojiPicker`, `FormaDateTimePicker` | **Host layer** over `watch`, its `readyAsync` baseline, `refreshAsync` and `signal`. `refresh`, after a sentinel's load, and `refreshAll`, after a reconnection, each deliver `watch.snapshot` once the refresh settles, since a refresh whose result equals the last raises no event. Each refresh can resample, since an observation that takes no new sample is read as it stands | A new sample on a sentinel's refresh ([D66]) | -| `DomEngine.js` | 76 | C#'s `DomEngine`: the freeze pane, the focus capabilities and the text fields' edits | **Host layer** over `executeAsync` and `run`, an interaction's commands among them; `scroll.step` becomes `scrollStep`. An execution that declares routes runs once `configureInput` has, as `DomInteraction` awaits the input policy before such an attach today | The owner ([D47]) | -| `OwnerWatcher.js` | 102 | The watcher's entry | **Host layer**: tokens, generations, and one `StateDelivery` per watch, fed by the `"change"` events after its first, each state crossing through the [browser transfer](browser-transfer-design.md), focus's every state sent as it is measured. The first event is the baseline `readyAsync` answers, which the attach returns: every listener's first `"change"` is the ready state, raised within the evaluation for one subscribed before it, and in a microtask after `subscribe` for one subscribed after ([DOMQL's test](https://github.com/FormaUI/DOMQL/blob/main/tests/dom/Watch.browser.js)). Sending both loads one extra page. A new generation starts a new watch with its bindings, and disposes the old one once the new one is ready | Change sets that compose, once they cross ([D65]) | -| `OwnerEngine.js` | 115 | The engine's entry | **Host layer** over `run`, the occurrences a behavior reports to its owner, and its commands, as the edits' `write`, `resend` and `flush`: a new generation updates the running execution, `update(bindings)`, which every behavior answers, and disposes it and runs it anew where the update fails. Since an update replaces the bindings whole, the host writes every option as a binding, as `wheel = wheel`, and declares the type of a structured one, as `{ buttons: 'FormaScrolling.ScrollButtons?' }`, which every update keeps | The owner ([D47]); declared binding types ([D82]) | -| `DomSession.js` | 61 | The entries | **Host layer**: an owner's elements, watcher and engine, released in order through one `AbortController` per part | — | -| `DomSessionRegistry.js` | 54 | The entries | **Host layer**: sessions by runtime key | — | -| `DomElement.js` | 80 | The session | **Host layer** for executions, ending each once a watch of `it.attached`, accepting partial observation, reads false; a watch follows a detached element back by itself, and `attached` catches the zero-sized removal its resize check misses | A watch of `attached`, where `run({ anchor })` is declined ([D74]) | -| `DomElements.js` | 29 | The session | **Host layer**, retiring with `DomElement` | — | -| `RegistrationTable.js` | 76 | The watcher and the engine | **Host layer**: tokens and generations; its resources become DOMQL handles | — | -| `StateDelivery.js` | 123 | The watcher | **Host layer**: one delivery in flight with the latest waiting, or, for focus, every state sent in the order it is measured, each as it is queued; suspension and resumption | Change sets coalesced by concatenation, or the latest snapshot whole ([D65]) | +| `DomWatcher.js` | 47 | C#'s `DomWatcher`: `FormaFreezePane`, `FormaExplorerContentArea`, `FormaEmojiPicker`, `FormaDateTimePicker` | **Retires into DOMQL.NET**: C#'s `DomWatcher` makes each watch through the component's owner, its first result arriving with its request's answer. A sentinel's refresh after a load takes a new sample and delivers the snapshot whole, changed or not, since a refresh whose result equals the last raises no event, and an observation that takes no new sample is read as it stands. DOMQL.NET's refresh of every watch after a reconnection delivers each snapshot whole too | A new sample on a sentinel's refresh ([D66]); [D119] | +| `DomEngine.js` | 76 | C#'s `DomEngine`: the freeze pane, the focus capabilities and the text fields' edits | **Retires into DOMQL.NET**: C#'s `DomEngine` runs each execution through the component's owner, an interaction's commands among them; `scroll.step` becomes `scrollStep`. An execution that declares routes runs once `configureInput` has, as `DomInteraction` awaits the input policy before such an attach today | The owner ([D47]) | +| `OwnerWatcher.js` | 102 | The watcher's entry | **Retires into DOMQL.NET**: its tokens and generations become a handle's, and its `StateDelivery` the connection's pacing. DOMQL.NET keeps each watch's copy, applies the change sets it is sent, and maps it onto the snapshot's type. Focus's watch waits for no acknowledgment, so each of its states crosses in order with the events after it. A new generation is the watch's update, whose next result is the first of its new bindings | Change sets that compose ([D65]); [D119], [D121] | +| `OwnerEngine.js` | 115 | The engine's entry | **Retires into DOMQL.NET**: a running execution is updated in place with its new bindings, which every behavior answers, and a refused update leaves it running as it was, so Forma's host layer disposes it and runs it anew. Since an update replaces the bindings whole, the host layer writes every option as a binding, as `wheel = wheel`, and declares the type of a structured one, as `{ buttons: 'FormaScrolling.ScrollButtons?' }`, which every update keeps | The owner ([D47]); declared binding types ([D82]) | +| `DomSession.js` | 61 | The entries | **Retires into DOMQL.NET**: an owner's handles, all ended in one request as the owner is disposed | The owner ([D47]) | +| `DomSessionRegistry.js` | 54 | The entries | **Retires into DOMQL.NET**: one connection for each browser runtime, holding its owners, each named by a component's runtime key | [D119] | +| `DomElement.js` | 80 | The session | **Retires into Forma's host layer**, which ends each execution once a watch of `it.attached`, accepting partial observation, reads false; a watch follows a detached element back by itself, and `attached` catches the zero-sized removal its resize check misses | A watch of `attached`, where `run({ anchor })` is declined ([D74]) | +| `DomElements.js` | 29 | The session | **Retires** with `DomElement` | — | +| `RegistrationTable.js` | 76 | The watcher and the engine | **Retires into DOMQL.NET**: its tokens and generations become a handle's, and its resources DOMQL handles | — | +| `StateDelivery.js` | 123 | The watcher | **Retires into DOMQL.NET**: one change in flight, those arising meanwhile joined, or, for focus's watch, which waits for no acknowledgment, each change crossing with its task. A batch the host can't take leaves the copy uncertain until a refresh brings its snapshot whole | Change sets coalesced by concatenation, or the latest snapshot whole ([D65]); [D121] | | `ResizeObserverPool.js` | 68 | `DomElement`, `ScrollStateObserver` | **Watch**: retires into DOMQL's `resize` observation, shared by target and box, which `scroll` holds on the track and, through the `children` target, on its children; `DomElement`'s removal check retires into the `attachment` observation `attached` holds | [D11] | | `IntersectionObserverPool.js` | 99 | `IntersectionStateObserver` | **Watch**: retires into `intersects({ root, margin })`, one observation for each element, root and margin, each with a native observer of its own, where the pool shares one native observer among every element of a root, margin and threshold; Forma uses threshold 0 alone | Its `remeasure` as `refreshAsync({ resample: true })` ([D66]) | -C# reads a whole state record from each observation today; no change set crosses yet. Once change sets cross, the host coalesces those waiting behind the delivery in flight by concatenating them, or sends the latest snapshot whole as one root replace ([D65]). +C# reads a whole state record from each observation today. Under DOMQL.NET change sets cross, each applied to the watch's copy, and the connection joins those that arise while one is unacknowledged ([D65]). -Until the C# half is designed ([D46]), this host layer carries everything to C#, and loads what each query needs: +DOMQL.NET carries everything to C# ([D119]), and Forma's host layer adds what is Forma's alone (F1): -- **Each watch's snapshots,** one delivery in flight, the latest waiting. -- **Each behavior's occurrences,** in order, through a bounded queue that never coalesces and fails on overflow, as Forma's [design](dom-watcher-engine-design.md) has it. DOMQL hands them over in the order they happen, across handles and owners ([D69]). -- **Each execution's answer.** A command that finds nothing running rejects with `DOMQL5016`, which the host answers as today's "the call didn't run". -- **Each Forma module, loaded first.** The host registers each module's loader with `domql.registerModuleLoader`, and awaits `domql.loadModulesAsync(query)` before carrying out a query that imports one ([D68]). A query it forgot to load for is refused with `DOMQL3007`. A module from outside `Forma.Framework.Browser.Interop`, as `FormaDataView`, `FormaRichText` or the Showcase's, reaches it with a loader by the module's name, where each C# wrapper names its script's path today; how a package or an app registers that loader is the host layer's to settle. +- **Each component's owner,** one `DomqlOwner` its context holds, named by its runtime key. Disposing it ends every watch, subscription and execution the component started, in one request, and each handle's failures reach the component's log. +- **Each watch's snapshots,** one change in flight, those arising meanwhile joined. Focus's watch waits for no acknowledgment, so each of its states crosses in order with the press or the key after it ([D121]). +- **Each behavior's occurrences,** in order, never joined, each handed to its handler as it is taken, whatever handler before it still awaits. DOMQL hands them over in the order they happen, across handles and owners ([D69]), and DOMQL.NET takes them in the order they cross. +- **Each execution's answer.** A command that finds nothing running fails with `DOMQL5016`, which the host layer answers as today's "the call didn't run". +- **Each Forma module, loaded first.** The host layer registers each module's loader with `domql.registerModuleLoader` in the browser, and asks DOMQL.NET to load a query's modules before carrying out a query that imports one ([D68]). A query it forgot to load for is refused with `DOMQL3007`. A module from outside `Forma.Framework.Browser.Interop`, as `FormaDataView`, `FormaRichText` or the Showcase's, reaches it with a loader by the module's name, where each C# wrapper names its script's path today; how a package or an app registers that loader is the host layer's to settle. +- **Reconnection.** A Server circuit's restored connection starts DOMQL.NET's refresh of every watch, and never awaits it, since a circuit handles one call from the browser at a time. ### Text @@ -478,7 +478,7 @@ DOMQL serves `readerWithin` today: a module's observation type with `notify`, `s | Script | Lines | Used by | Becomes | Rests on | Step | | --- | --- | --- | --- | --- | --- | -| `Dialog.js` | 77 | `FormaDialog` | **Once executions**, built in, which Forma's host layer carries out in one task, so they keep their order: `dialog.showModal()`, answering whether it opened it: false for a dialog open modally already, which `FormaDialog` counts as open, since today's `open` returns without reopening it, while a dialog open but not modal fails it. Then `dialog:focusFirst({ part = part })` of `FormaFocus`, `part` bound to the selector `focusWithin` gives, moving the focus to the first element Tab reaches within it, as `TabOrder` orders them, since Tab's order is no test of `tabindex` DOMQL's `focusable` could join ([D96]); it answers whether focus landed, null where the part or a control is missing. `CloseAsync` is `dialog.close()`, answering false for a dialog closed already, which `RequestCloseAsync` reads as a close that never ran, closing its own state, harmlessly. The scrim close is an opt-in continuous execution of `FormaPresentation`, `dialog:scrimClose()`, run only where `FormaDialog` closes on a scrim click. It is a click route on the input router that compares the click's original target with the dialog element, as the design's [native dialogs](dom-watcher-engine-design.md#native-dialogs) state. A click on the dialog's own box closes it inside the click, as today; a click on a descendant, empty space in a content wrapper included, leaves it open. Blazor's `@onclose` follows every close, as today | [D14], [D34], [D36], [D64]. A reaction ([D71]) doesn't fit the scrim close: it runs for every click its subscription hears | 10 | +| `Dialog.js` | 77 | `FormaDialog` | **Once executions**, built in, which one turn of `FormaDialog` makes, so they cross in one batch and DOMQL's connection carries them out in one task, keeping their order: `dialog.showModal()`, answering whether it opened it: false for a dialog open modally already, which `FormaDialog` counts as open, since today's `open` returns without reopening it, while a dialog open but not modal fails it. Then `dialog:focusFirst({ part = part })` of `FormaFocus`, `part` bound to the selector `focusWithin` gives, moving the focus to the first element Tab reaches within it, as `TabOrder` orders them, since Tab's order is no test of `tabindex` DOMQL's `focusable` could join ([D96]); it answers whether focus landed, null where the part or a control is missing. `CloseAsync` is `dialog.close()`, answering false for a dialog closed already, which `RequestCloseAsync` reads as a close that never ran, closing its own state, harmlessly. The scrim close is an opt-in continuous execution of `FormaPresentation`, `dialog:scrimClose()`, run only where `FormaDialog` closes on a scrim click. It is a click route on the input router that compares the click's original target with the dialog element, as the design's [native dialogs](dom-watcher-engine-design.md#native-dialogs) state. A click on the dialog's own box closes it inside the click, as today; a click on a descendant, empty space in a content wrapper included, leaves it open. Blazor's `@onclose` follows every close, as today | [D14], [D34], [D36], [D64]. A reaction ([D71]) doesn't fit the scrim close: it runs for every click its subscription hears | 10 | | `Frame.js` | 342 | `FormaFrame`, inside `FormaChrome` and `FormaWindow` | **Continuous execution** `frame:placement({ box = "self", dragRegion = …, handle = …, step = 10, bounds = null })` of `FormaPlacement`, offering `frame:placementChanges() { drag = it.drag, left = it.left, top = it.top, width = it.width, height = it.height }`, with the commands `measure` and `commit({ drag, left, top, width, height })`, since a `commit` names its drag. C# subscribes to `placementChanges` before it runs `placement`, since the behavior reports as it starts, centering an unplaced box, and an occurrence no subscription hears is lost (`DOMQL5017`). Its arrow keys become routes. Its size limits stay in the module. It holds its geometry and its `is-dragging` class through owned writes while it moves the frame. The render of `FormaFrame`, or of the `FormaWindow` presenting it, takes the accepted geometry over through `commit` (F3, [above](#owned-writes-beside-blazors-render)) | Occurrences ([D49]), commands ([D48]), the owner ([D47]), [D51], a null `bounds` ([D59]); owned writes beside Blazor's render ([D70]), handed over by `commit`; `env.observe` if it chooses ([D53]) | 10 | | `Splitter.js` | 75 | `FormaSplitter` | **Continuous execution** `bar:splitterDrag({ axis = "inline", action = "splitter.resize" })` of `FormaGestures`, offering `bar:splitterDrags() { phase = it.phase, travel = it.travel, canceled = it.canceled }`; its once-a-frame travel is the behavior's own, before it delivers | Occurrences in order ([D49], [D69]), the owner ([D47]), [D51]; its frame through `env.frame` ([D53]) or `FrameScheduler` | 9 | | `Virtualize.js` | 208 | `FormaVirtualize`: the data list, grid, cards and tree, and `FormaTimeBox`'s options | **Watch** of `start:virtualizer({ spacerAttribute = spacer }) { offset = it.offset, viewport = it.viewport, itemSize = it.itemSize }`, a maintained member of a nullable type, `VirtualizerMeasurement?` (NEXO4071), that `FormaVirtualizer` keeps with its own observation type. The watch's first snapshot waits for its first sample, and the snapshot is null while the start spacer is out of the document. Today's script reports nothing there, so C# skips a null snapshot. The observation type holds the measurement history and finds and observes the scroll container. `reveal` and `scrollTo` are once executions of the module, which find the drawn item or the offset's change and scroll instantly, answering at once, as the built-in `scrollIntoView` and `scrollBy` do for an instant scroll. The C# render, scroll and reveal loop stays C# | `env.observe` ([D53]); instant scrolls answering at once ([D35], [D67]) | 8 | @@ -511,8 +511,8 @@ DOMQL serves `readerWithin` today: a module's observation type with `notify`, `s | `Controls.js` | 12 | `InputRouter`, `FocusSurface`, `RovingFocus`, `ReorderInteraction`, `SelectionInteraction` | **Stays as it is**, for synchronous use in handlers (F2). In queries, `it.matches(…)` with its selectors, and `focusable` where a script asks whether an element can take focus; Tab's reach is `FormaFocus`'s `TabOrder`, since no test of `tabindex` gives the browser's order ([D96]). `focusable` differs from `Controls.Focusable`, which counts a hidden input, a disabled control holding a `tabindex`, and a box that isn't displayed; `textEditable` asks less than `Controls.Interactive` | In queries, [D14], [D96] | None | | `Direction.js` | 10 | `AnchoredPopover`, `Scroll`, `RovingFocus`, `ScrollContainer` | **Stays as it is**. In queries, `it.style["direction"]` is the computed direction it reads; `it.direction` is what `dir` decides, which a stylesheet's `direction` doesn't change | In queries, [D13] | None | | `FrameScheduler.js` | 34 | `DomElement`, `ScrollStateObserver`, `AnchoredPopover`, `DragGesture`, `Splitter`, `BlockAlignment`, `SelectionFollower` | **Stays as it is** for the plain classes that work without DOMQL (F2), the drag gesture's among them. Module code schedules through `env.frame(callback, { phase })`, a frame's writes before its reads, and a frame watch's handlers run inside the frame | For module code, [D53], [D63] | None | -| `Owner.js` | 15 | The reports of eleven scripts | **Host layer**: each report becomes a watch's change or a behavior's occurrence, which the host layer carries to C# in order, and `tell` retires with its last caller | Occurrences ([D49]), acknowledged ([D50]), in order across handles ([D69]) | With its callers | -| `Transfer.js` | 46 | Every script answering or reporting a value a reader can make large: the edits, the editor, the data view's range, the menu's document order, a print document | **Host layer**: the transfer itself, which the host layer applies to each snapshot, occurrence and answer it carries to C#, inline within its budget and as a stream beyond it, as [the browser transfer and the edit boundary](#the-browser-transfer-and-the-edit-boundary) set out | — | With its callers | +| `Owner.js` | 15 | The reports of eleven scripts | **Retires into DOMQL.NET**: each report becomes a watch's change or a behavior's occurrence, which DOMQL.NET carries to C# in order, and `tell` retires with its last caller | Occurrences ([D49]), acknowledged ([D50]), in order across handles ([D69]); [D119] | With its callers | +| `Transfer.js` | 46 | Every script answering or reporting a value a reader can make large: the edits, the editor, the data view's range, the menu's document order, a print document | **Retires into DOMQL.NET**, which carries each snapshot, occurrence and answer to C# inline within its budget and as a stream beyond it, as [the browser transfer and the edit boundary](#the-browser-transfer-and-the-edit-boundary) set out | [D119] | With its callers | | `Sanitizer.js` | 130 | The rich-text editor's Word paste | **Stays as it is**: a pure transform of markup | — | None | | `Scrolling.js` | 36 | `DragGesture`, `InputRouter` | **Stays as it is**, for their synchronous tests. In queries, `scroll` and `scrollContainer({ axis = "block" })`, which finds the nearest box the user can scroll whether or not its content overflows, starting at the element's flat-tree parent, where `nearestScroller` also asks that it overflow and tests the element itself first, as `DragGesture` asks it of its own element | In queries, [D9], [D10] | None | @@ -646,11 +646,20 @@ Selecting the item rows by their class leaves out the loading, empty and group-h ## The order of the work -DOMQL's own [order of the work](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md#planned-capabilities) holds one item, the C# half. Nothing in DOMQL blocks a step of Forma's, so what remains is Forma's work, step by step: +Nothing in DOMQL blocks a step of Forma's. DOMQL.NET, the C# half, has four of Forma's needs to meet before step 5 builds on it, the last three carried by DOMQL's connection already: + +| DOMQL.NET's work | Forma needs it for | +| --- | --- | +| A request's answers beyond the budget crossing as a stream, as a batch of deliveries does | A watch's first snapshot or an execution's answer past Blazor Server's message limit: the data view's range of tokens, the menu's document order, a taken text and a composed print document | +| A watch's refresh taking a new sample, the connection's `resample` | The sentinel's refresh after each load ([D66]) | +| A subscription's reactions | The copy and the share inside the press that asks for them, and the rich-text editor's commands inside the key's dispatch ([D71]) | +| Loading a query's modules, the connection's `load` | Every Forma module, loaded before a query that imports it ([D68]) | + +A test of DOMQL.NET through a real browser, in its gate, and its first release follow, on DOMQL `1.0.0-preview.5`, whose connection carries a watch that waits for no acknowledgment ([D121]). Then what remains is Forma's work, step by step: | Forma's step | Forma's work | Rests on | | --- | --- | --- | -| 5, the request model | The host layer over DOMQL: each module's loader, and every watch, execution and subscription carried to C#, one delivery in flight for each watch and a bounded queue of occurrences. Then the freeze pane, the sentinel, focus, the text count and the file viewer's centering on it | [D46], [D47], [D51], [D59], [D60], [D66], [D68], [D69], [D74]; the freeze pane's [D9], [D11], [D13], [D26], [D82]; the text count's [D70] | +| 5, the request model | The host layer over DOMQL.NET: each component's owner, each module's loader, focus's watch waiting for no acknowledgment, and the Server reconnection's refresh. Then the freeze pane, the sentinel, focus, the text count and the file viewer's centering on it | [D47], [D51], [D59], [D60], [D66], [D68], [D69], [D74], [D119], [D121]; the freeze pane's [D9], [D11], [D13], [D26], [D82]; the text count's [D70] | | 6, input routing | `FormaInput` over the input router, its routes and overrides bound with declared types; the wheel's turns; the inspector's two subscriptions, its wheels throttled | [D49], [D51], [D52], [D57], [D59], [D69], [D73], [D82] | | 7, anchored presentation | `FormaPlacement`'s anchored popover: its commands, and its `left` and `top` kept beside `FormaPopover`'s render, with the cost of updating them each frame measured against today's direct writes, the Android web view included | [D48], [D59], [D70] | | 8, virtualization | `FormaVirtualizer`: its maintained member, `reveal` and `scrollTo` | [D53], [D67] | @@ -665,7 +674,7 @@ DOMQL's own [order of the work](https://github.com/FormaUI/DOMQL/blob/main/docs/ Beside the steps: -- **The C# half,** A1, and A5's queue wait for their design ([D46], [D69]). Forma's host layer covers both from step 5. Once the C# half is designed, the host layer takes its typed queries and records and keeps its own transport (F1), as A1's [correction](#corrections-to-domqls-definitions) asks. +- **The C# half,** A1, is DOMQL.NET ([D119]), and A5's order is its connection's ([D69], [D121]). Forma's host layer builds on it from step 5 (F1). - **Forma's findings,** below, are Forma's to settle, each at the latest with the step that converts its script. ## Findings in Forma along the way @@ -741,7 +750,7 @@ Reading the scripts turned these up. None was reproduced, and each is Forma's to ### The explorer and the Showcase - **A drag the explorer never sees end stays its drag.** `ExplorerItemManager` records the dragged item at Blazor's `@ondragstart` and forgets it only on a drop it hears. The explorer handles no `dragend`, and neither the sidebar's drop zone, whose `TreeDropZoneOptions` set no `Accepts`, nor the breadcrumb tests what is dragged. So after a canceled drag, a file or text later dropped on a folder row or a crumb moves the earlier item: a canceled drag fires only `dragend`, which nothing handles; `FormaBreadcrumb` cancels `dragover` for any drag while it has an `OnItemDrop`; and its drop, like the sidebar's `HandleDropAsync`, calls `DropOnItemAsync`, which moves the item `BeginDrag` recorded. -- **The Showcase's sidebar has no Forma context.** It isn't a Forma component, and runs `ReadingPlace` through a `JSEnvironment` of its own with a fresh `Guid` (`ShowcaseSidebar.razor`), so it has no session or runtime key through which the host layer would run the reading place and its `reveal` command for an owner. +- **The Showcase's sidebar has no Forma context.** It isn't a Forma component, and runs `ReadingPlace` through a `JSEnvironment` of its own with a fresh `Guid` (`ShowcaseSidebar.razor`), so it has no runtime key or owner through which the host layer would run the reading place and its `reveal` command. ### The composer @@ -816,7 +825,6 @@ Reading the scripts turned these up. None was reproduced, and each is Forma's to [D42]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d42 [D43]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d43 [D44]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d44 -[D46]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d46 [D47]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d47 [D48]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d48 [D49]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d49 @@ -851,3 +859,6 @@ Reading the scripts turned these up. None was reproduced, and each is Forma's to [D87]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d87 [D88]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d88 [D96]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d96 +[D119]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d119 +[D121]: https://github.com/FormaUI/DOMQL/blob/main/docs/decisions.md#d121 +[DOMQL.NET]: https://github.com/FormaUI/DOMQL.NET diff --git a/docs/repository-structure.md b/docs/repository-structure.md index 406b3570..3615a48c 100644 --- a/docs/repository-structure.md +++ b/docs/repository-structure.md @@ -279,7 +279,9 @@ assembly's script by climbing to the content root, so the import survives a host **DOMQL**, the query language the DOM watcher and engine are designed to take, lives in its own repository, [DOMQL](https://github.com/FormaUI/DOMQL). It is a JavaScript library published as the package -`formaui-net.DOMQL`, whose one bundled file a host serves as `_content/domql/domql.js`. +`formaui-net.DOMQL`, whose one bundled file a host serves as `_content/domql/domql.js`. **DOMQL.NET**, DOMQL's own +.NET host, through which the watcher and engine reach DOMQL from C#, lives in its own repository too, +[DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), published as the package `formaui-net.DOMQL.NET`. [Replacing Forma's JavaScript with DOMQL](forma-javascripts-domql-replacement.md) sets out what each script becomes. **`FormaComposer` is the one component allowed external JavaScript libraries**, each to be confined to its own From 459defe297c037af4fc662ab2e2fc097f8df15b0 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 05:37:01 +0200 Subject: [PATCH 07/10] test: hold a script's answer until the test gives it, however long that takes bUnit fails each call a handler of its own holds without a result once its wait timeout, a second, has passed, so a held answer gave way on a loaded machine. --- .claude/skills/forma-testing/SKILL.md | 5 +- .../Components/Bars/FormaToolbarTests.razor | 3 +- .../Collections/FormaSortableListTests.razor | 3 +- .../Files/FormaFilePickerTests.razor | 6 ++- .../Inputs/FormaComboBoxTests.razor | 3 +- .../Inputs/FormaPasswordBoxTests.razor | 3 +- .../Components/Inputs/FormaTextBoxTests.razor | 3 +- .../Components/Inputs/FormaTimeBoxTests.razor | 3 +- .../Menus/FormaDropDownMenuTests.razor | 3 +- .../FormaRichTextEditorTests.razor | 3 +- .../Components/FormaDataViewTests.razor | 3 +- .../FormaExplorerTests.razor | 3 +- .../HeldCallHandler.cs | 52 +++++++++++++++++++ 13 files changed, 79 insertions(+), 14 deletions(-) create mode 100644 tests/support/Forma.Tests.Support.Blazor/HeldCallHandler.cs diff --git a/.claude/skills/forma-testing/SKILL.md b/.claude/skills/forma-testing/SKILL.md index 78ef887d..8976d3bc 100644 --- a/.claude/skills/forma-testing/SKILL.md +++ b/.claude/skills/forma-testing/SKILL.md @@ -46,8 +46,9 @@ bUnit renders markup and drives its own synchronous JS interop, so a green suite A test that passes alone and fails under load is broken, not unlucky: its assertion depends on how quickly a continuation is scheduled. Load only exposes the race. -- Do hold a component's asynchronous work in a fake the test controls, or in a script answer bUnit holds, and let it go through `cut.ReleaseAsync(...)` from the bUnit support project, which runs the release on the renderer and then takes a second turn there, so the component has acted once it returns and the test asserts directly after. -- Do give such a fake a plain `TaskCompletionSource`, which runs the component's continuation inline in the release; one created to run its continuations asynchronously, as bUnit's held script answers are, queues it on the renderer, which only the second turn waits out, so a release made any other way than through `ReleaseAsync` races it. +- Do hold a component's asynchronous work in a fake the test controls, or a script's answer in the bUnit support project's `HeldCallHandler` or `HeldVoidCallHandler`, and let it go through `cut.ReleaseAsync(...)` from the same project, which runs the release on the renderer and then takes a second turn there, so the component has acted once it returns and the test asserts directly after. +- Don't hold a script's answer in a handler bUnit sets up, `Setup` or `SetupVoid` left without a result: bUnit fails each call such a handler holds once `BunitContext.DefaultWaitTimeout`, a second, has passed, so on a loaded machine the component meets a failed call where the test meant a held one. +- Do give such a fake a plain `TaskCompletionSource`, which runs the component's continuation inline in the release; one created to run its continuations asynchronously queues it on the renderer, which only the second turn waits out, so a release made any other way than through `ReleaseAsync` races it. - Do hand a fake's answer on through a continuation that runs synchronously, `ContinueWith` with `ExecuteSynchronously`, where it has to convert it; an await with `ConfigureAwait(false)` completing under the renderer's context is queued to the thread pool, and the component's continuation with it. - 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. diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Bars/FormaToolbarTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Bars/FormaToolbarTests.razor index dbe3dc2c..8af69a56 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Bars/FormaToolbarTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Bars/FormaToolbarTests.razor @@ -842,7 +842,8 @@ { // Arrange — the input router's configuration, which the shortcuts' registration waits for, held in the browser using var ctx = new FormaToolbarTests(); - var configure = ctx.Router.SetupVoid("configure", _ => true); + var configure = new HeldVoidCallHandler("configure"); + ctx.Router.AddInvocationHandler(configure); var groups = Group( new ToolbarCommand { Id = "bold", Title = "Bold", Command = "bold", ShortcutAriaKeys = "Control+B" }, new ToolbarCommand { Id = "italic", Title = "Italic", Command = "italic" }); diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Collections/FormaSortableListTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Collections/FormaSortableListTests.razor index 3d994b5d..03846f8b 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Collections/FormaSortableListTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Collections/FormaSortableListTests.razor @@ -30,7 +30,8 @@ { // Arrange — the input router's configuration, which the reordering attaches after, held in the browser using var ctx = new FormaSortableListTests(); - var configure = ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").SetupVoid("configure", _ => true); + var configure = new HeldVoidCallHandler("configure"); + ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").AddInvocationHandler(configure); var items = CreateItems(2); var cut = ctx.Render( @ diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Files/FormaFilePickerTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Files/FormaFilePickerTests.razor index c75feb1d..8ba46134 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Files/FormaFilePickerTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Files/FormaFilePickerTests.razor @@ -264,7 +264,8 @@ { // Arrange — cleared while its drop zone still waits on the input router's configuration to attach using var ctx = new FormaFilePickerTests(); - var configure = ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").SetupVoid("configure", _ => true); + var configure = new HeldVoidCallHandler("configure"); + ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").AddInvocationHandler(configure); var dropZone = ctx.JSInterop.SetupModule("./_content/forma/browser/scripts/behaviors/FileDropZone.js").SetupModule("attach", _ => true); dropZone.Mode = JSRuntimeMode.Loose; var cut = ctx.Render(@); @@ -283,7 +284,8 @@ { // Arrange — cleared while its drop zone still waits to attach, then a file chosen using var ctx = new FormaFilePickerTests(); - var configure = ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").SetupVoid("configure", _ => true); + var configure = new HeldVoidCallHandler("configure"); + ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").AddInvocationHandler(configure); var dropZone = ctx.JSInterop.SetupModule("./_content/forma/browser/scripts/behaviors/FileDropZone.js").SetupModule("attach", _ => true); dropZone.Mode = JSRuntimeMode.Loose; var cut = ctx.Render(@); diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaComboBoxTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaComboBoxTests.razor index ac7f4c83..26fe7afe 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaComboBoxTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaComboBoxTests.razor @@ -77,7 +77,8 @@ using var ctx = new FormaComboBoxTests(); var engine = ctx.JSInterop.SetupModule(FakeDomBrowser.EnginePath); engine.Mode = JSRuntimeMode.Loose; - var attach = engine.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + engine.AddInvocationHandler(attach); var model = new FakeModel { Status = 2 }; var cut = ctx.Render(@ diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaPasswordBoxTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaPasswordBoxTests.razor index 337f0efe..bc0f2a28 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaPasswordBoxTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaPasswordBoxTests.razor @@ -27,7 +27,8 @@ using var ctx = new FormaPasswordBoxTests(); var engine = ctx.JSInterop.SetupModule(FakeDomBrowser.EnginePath); engine.Mode = JSRuntimeMode.Loose; - var attach = engine.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + engine.AddInvocationHandler(attach); var model = new FakeModel(); var cut = ctx.Render(@ diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTextBoxTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTextBoxTests.razor index ec3b68ba..82c92570 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTextBoxTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTextBoxTests.razor @@ -287,7 +287,8 @@ using var ctx = new FormaTextBoxTests(); var engine = ctx.JSInterop.SetupModule(FakeDomBrowser.EnginePath); engine.Mode = JSRuntimeMode.Loose; - var attach = engine.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + engine.AddInvocationHandler(attach); var model = new FakeModel(); var cut = ctx.Render(@ diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTimeBoxTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTimeBoxTests.razor index 50b14fcc..4a1540d7 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTimeBoxTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Inputs/FormaTimeBoxTests.razor @@ -30,7 +30,8 @@ using var ctx = new FormaTimeBoxTests(); var engine = ctx.JSInterop.SetupModule(FakeDomBrowser.EnginePath); engine.Mode = JSRuntimeMode.Loose; - var attach = engine.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + engine.AddInvocationHandler(attach); var cut = ctx.Render(@); var field = cut.FindComponent(); var disposal = cut.InvokeAsync(() => field.Instance.DisposeAsync().AsTask()); diff --git a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Menus/FormaDropDownMenuTests.razor b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Menus/FormaDropDownMenuTests.razor index d74ab0da..42b39831 100644 --- a/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Menus/FormaDropDownMenuTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.BUnit.Tests/Components/Menus/FormaDropDownMenuTests.razor @@ -563,7 +563,8 @@ { // Arrange — the browser's answer of where the items stand held while an item is clicked, which closes the menu using var ctx = new FormaDropDownMenuTests(); - var sort = ctx.JSInterop.SetupModule("./_content/forma/browser/scripts/operations/DocumentOrder.js").Setup("sort", _ => true); + var sort = new HeldCallHandler("sort"); + ctx.JSInterop.SetupModule("./_content/forma/browser/scripts/operations/DocumentOrder.js").AddInvocationHandler(sort); var cut = ctx.Render( @ Options diff --git a/tests/bunit/Blazor/Forma.Blazor.Composer.BUnit.Tests/RichTextEditor/FormaRichTextEditorTests.razor b/tests/bunit/Blazor/Forma.Blazor.Composer.BUnit.Tests/RichTextEditor/FormaRichTextEditorTests.razor index 16b779ae..d4b60a36 100644 --- a/tests/bunit/Blazor/Forma.Blazor.Composer.BUnit.Tests/RichTextEditor/FormaRichTextEditorTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.Composer.BUnit.Tests/RichTextEditor/FormaRichTextEditorTests.razor @@ -398,7 +398,8 @@ ctx.JSInterop.SetupModule(CanvasPath).SetupModule("attach", _ => true); var engine = ctx.JSInterop.SetupModule(Forma.Tests.Browser.FakeDomBrowser.EnginePath); engine.Mode = JSRuntimeMode.Loose; - var attach = engine.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + engine.AddInvocationHandler(attach); var model = new TestModel(); var cut = ctx.Render(@); var whileAttaching = (GetCanvas(cut).GetAttribute("contenteditable"), GetCanvas(cut).GetAttribute("aria-disabled")); diff --git a/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor b/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor index 35027a55..7501a282 100644 --- a/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.DataView.BUnit.Tests/Components/FormaDataViewTests.razor @@ -931,7 +931,8 @@ { // Arrange — the input router's configuration, which the script acting on the items' presses and keys attaches after, held in the browser using var ctx = new FormaDataViewTests(); - var configure = ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").SetupVoid("configure", _ => true); + var configure = new HeldVoidCallHandler("configure"); + ctx.JSInterop.SetupModule("./_content/forma/input/scripts/InputRouter.js").AddInvocationHandler(configure); var products = new[] { new Product(1, "Hammer"), new Product(2, "Atlas") }; var cut = ctx.Render( @ diff --git a/tests/bunit/Blazor/Forma.Blazor.Explorer.BUnit.Tests/FormaExplorerTests.razor b/tests/bunit/Blazor/Forma.Blazor.Explorer.BUnit.Tests/FormaExplorerTests.razor index 7f609984..e207ef8b 100644 --- a/tests/bunit/Blazor/Forma.Blazor.Explorer.BUnit.Tests/FormaExplorerTests.razor +++ b/tests/bunit/Blazor/Forma.Blazor.Explorer.BUnit.Tests/FormaExplorerTests.razor @@ -2726,7 +2726,8 @@ using var ctx = new FormaExplorerTests(); var watcher = ctx.JSInterop.SetupModule(Forma.Tests.Browser.FakeDomBrowser.WatcherPath); watcher.Mode = JSRuntimeMode.Loose; - var attach = watcher.Setup("attach", _ => true); + var attach = new HeldCallHandler("attach"); + watcher.AddInvocationHandler(attach); IReadOnlyList folders = [new FolderResourceInfo("races") { Name = "Races" }]; var cut = ctx.Render(@); cut.WaitForState(() => GetFolderRows(cut).Count == 2); diff --git a/tests/support/Forma.Tests.Support.Blazor/HeldCallHandler.cs b/tests/support/Forma.Tests.Support.Blazor/HeldCallHandler.cs new file mode 100644 index 00000000..4ab32461 --- /dev/null +++ b/tests/support/Forma.Tests.Support.Blazor/HeldCallHandler.cs @@ -0,0 +1,52 @@ +namespace Forma.Tests.Blazor; + +using Bunit; + +using Microsoft.JSInterop.Infrastructure; + +/// A bUnit invocation handler that holds every call to identifier until the test answers them, then answers each later call at once. +/// +/// The calls wait on a plain of the handler's own, so each caller's continuation runs inline where +/// answers it, and the calls wait however long the test takes. A handler bUnit sets up keeps its calls apart and fails +/// each one it holds unanswered with JSRuntimeInvocationNotSetException once has passed. +/// +/// The type the calls answer. +/// The function the handler answers. +public class HeldCallHandler(string identifier) + : JSRuntimeInvocationHandlerBase(invocation => invocation.Identifier == identifier, isCatchAllHandler: false) +{ + private readonly TaskCompletionSource _answer = new(); + + private readonly List _heldCalls = []; + + /// The calls made so far, in order. + public IReadOnlyList HeldCalls + => [.. _heldCalls]; + + /// Answers every call held with , and every later call. + /// The answer. + public void SetResult(TResult result) + => _answer.SetResult(result); + + /// + protected override Task HandleAsync(JSRuntimeInvocation invocation) + { + _heldCalls.Add(invocation); + + return _answer.Task; + } +} + +/// A bUnit invocation handler that holds every call to identifier answering nothing until the test answers them, then answers each later call at once. +/// The function the handler answers. +public sealed class HeldVoidCallHandler(string identifier) + : HeldCallHandler(identifier) +{ + /// + public override bool IsVoidResultHandler + => true; + + /// Answers every call held, and every later call. + public void SetVoidResult() + => SetResult(null!); +} From 43281a3676ddeb25414d1327d1913c992d2be36f Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 05:37:54 +0200 Subject: [PATCH 08/10] docs(domql): load a query's modules before it, and wait on reaction results for the copy and the share --- docs/dom-watcher-engine-design.md | 5 +++-- docs/forma-javascripts-domql-replacement.md | 14 ++++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/dom-watcher-engine-design.md b/docs/dom-watcher-engine-design.md index ccb84be5..edb85f8b 100644 --- a/docs/dom-watcher-engine-design.md +++ b/docs/dom-watcher-engine-design.md @@ -234,8 +234,9 @@ DOMQL keeps document-level infrastructure only while subscribers need it. Native A managed-to-browser invocation on Blazor Server normally waits for a network response. Browser-to-managed notifications and module fetches are counted separately, so optimizing one does not hide the cost of another. -- **One connection per runtime scope.** DOMQL.NET's connection opens as its first request crosses, importing its browser module, which loads DOMQL. The scope is a circuit on Server, the client application's service lifetime on WebAssembly and a web view's in Blazor Hybrid. Loading a Forma module is a separate network fetch, asked for through the same connection before the first query that imports it. -- **One call per turn.** Every request a turn of the renderer makes crosses in one call as the turn ends: the watches, subscriptions and executions it starts, and the module loads they need. Required input-policy configuration remains visible in the crossing count. +- **One connection per runtime scope.** DOMQL.NET's connection opens as its first request crosses, importing its browser module, which loads DOMQL. The scope is a circuit on Server, the client application's service lifetime on WebAssembly and a web view's in Blazor Hybrid. Loading a Forma module is a separate network fetch. +- **One call per turn.** Every request a turn of the renderer makes crosses in one call as the turn ends: the watches, subscriptions and executions it starts. Required input-policy configuration remains visible in the crossing count. +- **A module's load first.** A query importing a Forma module crosses once the module's load, asked for through the same connection, has answered, since the browser carries out a batch's requests before a load in it completes: one crossing for each module in each document. - **The first snapshot in the answer.** A read is one invocation returning its snapshot. A watch's request answers with its first snapshot, which the watcher delivers as its first notification, saving a separate initial callback. - **One call for each browser task's deliveries.** A watch's changes, a subscription's events and late answers that arise in one browser task cross together. - **No call for an unchanged, applied request.** `SyncAsync` compares target and options against successfully applied state. An equal request still retries inactive or known-invalid state. `RefreshAsync` explicitly requests a browser read even when options are equal; local equality cannot prove browser health. diff --git a/docs/forma-javascripts-domql-replacement.md b/docs/forma-javascripts-domql-replacement.md index 18d5aed5..f4bc0120 100644 --- a/docs/forma-javascripts-domql-replacement.md +++ b/docs/forma-javascripts-domql-replacement.md @@ -51,7 +51,7 @@ In this document: ## The verdict -DOMQL's model fits Forma, and nothing in DOMQL blocks Forma's plan any longer. DOMQL.NET, through which Forma's C# reaches it, has four of Forma's needs to meet and its first release to make before step 5 builds on it. +DOMQL's model fits Forma. One gap in DOMQL's connection remains for step 11: a subscription's event crosses without its reactions' results. DOMQL.NET, through which Forma's C# reaches DOMQL, has four of Forma's needs to meet and its first release to make before step 5 builds on it. - **Every capability the survey asked of DOMQL is settled.** Each V, E, O, X, C, T and A item is implemented, or declined with an alternative Forma uses, by a decision of DOMQL's. [What Forma uses of DOMQL](#what-forma-uses-of-domql) gives each one's decision and the scripts that use it. - **The two gaps the recheck found are closed:** @@ -140,7 +140,7 @@ DOMQL settled every capability the survey asked of it. Each table gives, for eac - **Used by:** the Forma scripts that use it, in the form this document chooses for them; - **Also:** the scripts another form would use it for, an improvement on today's behavior, or a cost it saves. -No capability blocks a step. Each is defined in DOMQL's [specification](https://github.com/FormaUI/DOMQL/blob/main/spec/README.md), which its decision links to, and summarized here in a few words. +No capability blocks a step but A7's results, which DOMQL's connection doesn't carry to a host yet, as [the order of the work](#the-order-of-the-work) sets out. Each is defined in DOMQL's [specification](https://github.com/FormaUI/DOMQL/blob/main/spec/README.md), which its decision links to, and summarized here in a few words. ### The language @@ -249,7 +249,7 @@ DOMQL's [API and host](https://github.com/FormaUI/DOMQL/blob/main/docs/features- | A4 | Modules loaded on request, `domql.registerModuleLoader` and `domql.loadModulesAsync` | [D68]. Nothing loads a module implicitly: a request importing a module whose loader hasn't run yet is refused with `DOMQL3007`. The connection loads one through its `load` request | Every Forma module, through the loaders Forma's host layer registers and the loads it asks for before a query (F1) | — | | A5 | Ordered occurrence delivery to C# | The JavaScript side ([D69]): what DOMQL delivers reaches its handlers in the order it happens, across handles and owners. DOMQL.NET takes each delivery in the order it crossed, an event never waiting for a watch's acknowledgment or a handler ([D119]), and a host that leaves 4,096 deliveries unacknowledged has its connection closed with `DOMQL5026`. In a Blazor Web App of its own, a queue that sent each only once .NET had completed the one before let a button's click overtake an editor's flush on blur in every run, Server and WebAssembly | `InputRouter.js`, `DropZone.js`, `ReorderInteraction.js`, `Wheel.js`, `Splitter.js`, `SelectionInteraction.js`, `RichTextEditor.js`, `CultureCoordinator.js`; `Owner.js`'s reports | — | | A6 | An execution's lifetime anchored to its element | Declined ([D74]): the caller watches `attached` and disposes the execution once it reads false | `DomElement.js`, `DomElements.js`, `OwnerEngine.js`, retiring into Forma's host layer, which ends an execution through a watch of `it.attached` | — | -| A7 | Reactions: once executions a subscription carries out inside each event's delivery, `event` bound, before its handler, so they keep the user's activation | [D71] | `Clipboard.js` and `Share.js`: the copy and the share inside the press that asks for them. `RichTextEditor.js`: its editor commands inside the key's dispatch, through a dictionary from the router's action to the editor's command, and a paste from a menu inside its press | `Dialog.js`'s scrim close, which a reaction doesn't fit, since it runs for every click its subscription hears. `TextEntry.js`'s selection after Go, which waits for C#'s render of the entry | +| A7 | Reactions: once executions a subscription carries out inside each event's delivery, `event` bound, before its handler, so they keep the user's activation | [D71] | `Clipboard.js` and `Share.js`: the copy and the share inside the press that asks for them, their results reaching C# once DOMQL's connection carries them with the event. `RichTextEditor.js`: its editor commands inside the key's dispatch, through a dictionary from the router's action to the editor's command, and a paste from a menu inside its press | `Dialog.js`'s scrim close, which a reaction doesn't fit, since it runs for every click its subscription hears. `TextEntry.js`'s selection after Go, which waits for C#'s render of the entry | | A8 | The element a watch's list item came from, `watch.sourceOf(...path)` | [D72] | — | `BlockAlignment.js` as a watch | | A9 | A delayed schedule, which a refresh flushes; reporting on parts; a subscription's throttle. Delivery by frame is declined, since a throttle paces events and what a frame renders reads the latest itself | [D73] | `InputInspector.js`: a throttle keeping the latest wheel decision, on a subscription to wheels of its own. `TextEntry.js`: the plain text editor's selection watched under a delay | — | | A10 | Ownership of writes against Blazor's render: each target the framework's or an owned write's, `ownText` for a rendered text, a kept value yielding to another holder, and only to one restoring its own value; isolated layers declined | [D70], [D83] | `AnchoredPopover.js` (inline `left` and `top`), `Frame.js` (its geometry and `is-dragging`), `FileDropZone.js`, `ReorderInteraction.js`, `AutofillTracker.js`, `SelectionFollower.js` (classes), `BlockAlignment.js` (a row's `hidden`), `CharacterCount.js` (a rendered text node); `RovingFocus.js`, latent (`tabindex`) | — | @@ -324,7 +324,7 @@ A Blazor Web App of its own showed why the boundary is needed, Server and WebAss ## The scripts, one by one -Each row says who uses the script, what it becomes, what of DOMQL it rests on, and the step that converts it. Nothing a row rests on is missing from DOMQL: +Each row says who uses the script, what it becomes, what of DOMQL it rests on, and the step that converts it. Nothing a row rests on is missing from DOMQL but the results of `Clipboard.js`' and `Share.js`' reactions, which DOMQL's connection doesn't carry to a host yet: - **The C# half** is DOMQL.NET (A1, [D119]), which carries every snapshot, occurrence and execution answer to C#, under Forma's host layer (F1). - **Every Forma module** is loaded through the loader the host layer registers for it, before a query that imports it (A4, [D68]), so no row lists A4. @@ -389,7 +389,7 @@ DOMQL.NET carries everything to C# ([D119]), and Forma's host layer adds what is - **Each watch's snapshots,** one change in flight, those arising meanwhile joined. Focus's watch waits for no acknowledgment, so each of its states crosses in order with the press or the key after it ([D121]). - **Each behavior's occurrences,** in order, never joined, each handed to its handler as it is taken, whatever handler before it still awaits. DOMQL hands them over in the order they happen, across handles and owners ([D69]), and DOMQL.NET takes them in the order they cross. - **Each execution's answer.** A command that finds nothing running fails with `DOMQL5016`, which the host layer answers as today's "the call didn't run". -- **Each Forma module, loaded first.** The host layer registers each module's loader with `domql.registerModuleLoader` in the browser, and asks DOMQL.NET to load a query's modules before carrying out a query that imports one ([D68]). A query it forgot to load for is refused with `DOMQL3007`. A module from outside `Forma.Framework.Browser.Interop`, as `FormaDataView`, `FormaRichText` or the Showcase's, reaches it with a loader by the module's name, where each C# wrapper names its script's path today; how a package or an app registers that loader is the host layer's to settle. +- **Each Forma module, loaded first.** The host layer registers each module's loader with `domql.registerModuleLoader` in the browser, and has DOMQL.NET load a query's modules, awaiting the load, before carrying out a query that imports one ([D68]), since the browser carries out a batch's requests before a load in it completes. A query it forgot to load for is refused with `DOMQL3007`. A module from outside `Forma.Framework.Browser.Interop`, as `FormaDataView`, `FormaRichText` or the Showcase's, reaches it with a loader by the module's name, where each C# wrapper names its script's path today; how a package or an app registers that loader is the host layer's to settle. - **Reconnection.** A Server circuit's restored connection starts DOMQL.NET's refresh of every watch, and never awaits it, since a circuit handles one call from the browser at a time. ### Text @@ -646,7 +646,9 @@ Selecting the item rows by their class leaves out the loading, empty and group-h ## The order of the work -Nothing in DOMQL blocks a step of Forma's. DOMQL.NET, the C# half, has four of Forma's needs to meet before step 5 builds on it, the last three carried by DOMQL's connection already: +DOMQL's connection has one gap left for Forma: a subscription's event crosses as its projected value alone, so the results of its reactions never reach the host. The copy and the share need them, since C# answers how the browser took each, so step 11 waits for an event delivery that carries them. + +DOMQL.NET, the C# half, has four of Forma's needs to meet before step 5 builds on it, the last three carried by DOMQL's connection already: | DOMQL.NET's work | Forma needs it for | | --- | --- | From 7818bab25648b26f39fefc0cfc00ca82a9c7b9fc Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 05:44:41 +0200 Subject: [PATCH 09/10] chore: release 1.0.0-preview.26 --- CHANGELOG.md | 2 +- docs/features-status.md | 2 +- src/Framework/Forma.Framework.Localization/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf138a4b..4cdc5dd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ set out. What Forma gained before its first release, month by month, is in [the ## `1.0.0-preview.26` -*Unreleased* +*December 3, 2026* - A [labeled field](docs/component-catalog.md#formafield)'s resting label stands centered on its box again, and over a `FormaTextArea` level with where a one-line field's rests, where it sat on the value's line at the box's lower edge diff --git a/docs/features-status.md b/docs/features-status.md index 096ecbdb..9c4d8a3a 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.25` | +| 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.26` | | 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. diff --git a/src/Framework/Forma.Framework.Localization/README.md b/src/Framework/Forma.Framework.Localization/README.md index f2c8855a..e24d446f 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: - + From 1e74d83d0d26ce63301174739dadd0c85c97dff8 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:31:28 +0200 Subject: [PATCH 10/10] test(transfer): wait in the page for what a save of megabytes leaves there --- .../Components/TransferTests.cs | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs index c1127f06..b2ef41ed 100644 --- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs +++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs @@ -46,14 +46,19 @@ private static string Describe(string value) 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) + // Waits in the page for the text a save leaves in the element selector names, the whole of it or a part, then asserts it, failing with + // what each field holds in the browser and whether its edits listen. An assertion that finds its text not yet there describes the page on + // every poll, the megabytes its fields hold among it, which holds the page from drawing the save it waits for. + private static async Task ExpectSavedAsync(IPage page, string selector, string text, bool isPart = false) { try { - await expectation(); + await page.WaitForFunctionAsync( + "([selector, text, isPart]) => { const saved = (document.querySelector(selector)?.textContent ?? '').replace(/\\s+/g, ' ').trim(); return isPart ? saved.includes(text) : saved === text; }", + new object[] { selector, text, isPart }, + new() { Timeout = 30_000 }); } - catch (PlaywrightException exception) + catch (TimeoutException exception) { string fields; @@ -66,8 +71,11 @@ private static async Task ExpectSavedAsync(IPage page, Func expectation) 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}"); + Assert.Fail($"{selector} didn't come to hold {(isPart ? "a text containing" : "the text")} '{text}': {exception.Message}{Environment.NewLine}The forms' fields: {fields}"); } + + var saved = Assertions.Expect(page.Locator(selector)); + await (isPart ? saved.ToContainTextAsync(text) : saved.ToHaveTextAsync(text)); } public sealed class Forms(BrowserHost host) @@ -88,7 +96,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 ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-notes-saved")).ToHaveTextAsync(Describe(notes), Reached)); + await ExpectSavedAsync(page, "#forma-notes-saved", Describe(notes)); await Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1"); } @@ -107,7 +115,7 @@ public async Task Should_save_the_last_word_typed_into_the_rich_text_editor_insi await page.Locator("#forma-save").ClickAsync(); // Assert - await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-body-end")).ToContainTextAsync("Hello world")); + await ExpectSavedAsync(page, "#forma-body-end", "Hello world", isPart: true); } [Theory] @@ -126,7 +134,7 @@ public async Task Should_save_a_document_of_megabytes_pasted_into_the_rich_text_ await page.Locator("#forma-save").ClickAsync(); // Assert - await ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#forma-body-saved")).ToHaveTextAsync(Describe(document), Reached)); + await ExpectSavedAsync(page, "#forma-body-saved", Describe(document)); } [Theory] @@ -147,7 +155,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 ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#host-saved")).ToHaveTextAsync($"Ada {Describe(notes)}", Reached)); + await ExpectSavedAsync(page, "#host-saved", $"Ada {Describe(notes)}"); await Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1"); } @@ -175,7 +183,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 ExpectSavedAsync(page, () => Assertions.Expect(page.Locator("#saves")).ToHaveTextAsync("1")); + await ExpectSavedAsync(page, "#saves", "1"); } }