Skip to content

Latest commit

 

History

History
694 lines (617 loc) · 39.8 KB

CLAUDE.md

File metadata and controls

694 lines (617 loc) · 39.8 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Build and Development Commands

Building the Project

# Restore dependencies and build
dotnet restore
dotnet build

# Build in Release mode
dotnet build --configuration Release

# Build with warnings as errors (for CI/CD validation)
dotnet build /p:TreatWarningsAsErrors=true

# Create local NuGet package
./pack-local.sh  # macOS/Linux - Creates packages in ./nupkg/
./pack-local.ps1 # Windows

Code style (.editorconfig) — enforced in CI, not in the build

dotnet run build.cs -- format            # the CI gate: verify only, fails on any diff
dotnet format FormCraft.sln              # apply the fixes
dotnet format FormCraft.sln whitespace   # or scope it: whitespace only
dotnet format FormCraft.sln style        # ...or the IDE* code-style rules only
  • EnforceCodeStyleInBuild is deliberately NOT set, so IDE* analyzers do not run during dotnet build. That is why .editorconfig's warning severities never met TreatWarningsAsErrors and 574 violations accumulated across 201 files before #301 — the two settings look like enforcement together and are not. ⛔ Don't "fix" that by switching the property on: with warnings-as-errors, one missing brace would break dotnet build mid-edit and every incremental build would pay for the analyzer pass. The Format CI step is where regression is caught.
  • ⚠️ dotnet format can corrupt multi-targeted files when it applies fixes. FormCraft is net8.0;net10.0;net11.0, and a fix applied once per TFM can land as a literal <<<<<<< TODO: Unmerged change from project 'FormCraft(net10.0)' conflict block written into the .cs file — code that does not compile (measured in #301 on FieldRendererBase.cs). Verify mode never writes, so CI is safe. The guard is FormCraft.UnitTests/Ci/ConflictMarkerTests (#347) — it fails dotnet test if a tracked .cs file carries a marker, so a corrupted file cannot reach dev unnoticed. grep -rl '<<<<<<< TODO' --include='*.cs' . is still useful as a quick diagnostic right after an apply run, but the test is what actually enforces this.
  • ⚠️ One dotnet format run does not always reach a fixpoint. Measured in #301: after formatting a field-keyword property, verify still reported three WHITESPACE diagnostics on it, and a second run cleared them. If the format target fails right after you formatted, run the formatter again before assuming the gate is wrong.
  • IDE0032 now rewrites a private backing field into C# 14's field keyword. Value-identical, but it silently deletes the XML docs that lived on the field — which on MudBlazorFileUploadComponentBase.RequiredDescriptionId were documenting a real correctness invariant (#262: the hint id must be unique per rendered instance). Read those hunks; move the explanation onto the property rather than losing it.

Running Tests

The test projects are Microsoft.Testing.Platform (MTP 2.x, xunit.v3 4.x) hosts, not VSTest, and global.json opts dotnet test in to the SDK's native MTP mode ("test": { "runner": "Microsoft.Testing.Platform" }, #371) — without it dotnet test refuses to run them at all. That changes how you filter — see the warning below the commands.

# Run everything — ~1,700 tests across the three test projects (approximate on purpose: the
# exact figure drifts with every merge, and a stale precise number reads as authoritative)
dotnet test -c Release

# Run one test project. `-c Release` throughout: CI runs Release, and the host path
# below is a Release path — mixing configurations is how you end up running one build
# and inspecting another.
dotnet test FormCraft.UnitTests/FormCraft.UnitTests.csproj -c Release
dotnet test FormCraft.ForMudBlazor.UnitTests/FormCraft.ForMudBlazor.UnitTests.csproj -c Release
dotnet test FormCraft.ForFluentUI.UnitTests/FormCraft.ForFluentUI.UnitTests.csproj -c Release

# Run one class — everything after `--` is forwarded to the test host.
# Always name the .csproj: run solution-wide, the filter is applied to all three
# assemblies and the two that match nothing report Zero tests ran, exiting 8.
dotnet test FormCraft.UnitTests/FormCraft.UnitTests.csproj -c Release \
  -- --filter-class FormCraft.UnitTests.Ci.GitignoreTests

# Same filter without the build step (~200ms). Run `dotnet build -c Release` first,
# or you are testing a stale binary. On Windows the host is `...\FormCraft.UnitTests.exe`.
FormCraft.UnitTests/bin/Release/net10.0/FormCraft.UnitTests \
  --filter-class FormCraft.UnitTests.Ci.GitignoreTests

Filters: --filter-class, --filter-method, --filter-namespace, --filter-trait, --filter-uid, --filter-query, plus a --filter-not-* counterpart for class/method/namespace/trait. * wildcards work at either end, and the simple filters cannot be combined with --filter-query. --filter-method wants the fully-qualified name (<namespace>.<class>.<method>) — a bare method name matches nothing. --filter-trait is useless here: no test in this repo carries a [Trait].

⚠️ The VSTest spellings are inconsistent under native MTP mode — don't reach for them. dotnet test <csproj> --filter "FullyQualifiedName~…" now really filters (it used to be ignored with MTP0001). --collect "XPlat Code Coverage" now fails loudly (Zero tests ran, exit 5); coverage is still not wired up (no MTP coverage extension is referenced). ⛔ The MSBuild-property spelling -p:VSTestTestCaseFilter=… is still silently inert — the whole project runs, exit 0, and not even a warning. FormCraft.UnitTests/Ci/ClaudeMdTestCommandsTests fails — it is a unit test, so dotnet test catches this, not dotnet build — if a --collect, --logger or -p:VSTest… command returns to this file.

⚠️ A green-looking run may have run nothing.

  • One aggregate summary. dotnet test prints a single Test run summary: <verdict> block naming every assembly it ran, then total: / failed: / succeeded: / skipped: on separate lines — the verdict and the count never share a line.
  • $? is only meaningful unpiped. | tail / | grep replaces it with the pipe's 0.
  • Filter matching nothing → Zero tests ran, total: 0, exit 8, on both paths. A solution-wide -- --filter-class … is this case for two of the three assemblies: aggregate Failed!, error: 2, exit 8 — hence "always name the .csproj".
  • Mistyped flag → exit 5. Through dotnet test it looks like an empty filter (Zero tests ran, error: 1, no Unknown option text), so the exit code — 5 vs 8 — is the only tell. The direct host prints Unknown option '--…' plus the full --help and no summary line at all (so grep 'Failed!' reads it as green).

This block is a summary. The authoritative version — the full flag list, the failure modes, and the measurements behind every claim — is .claude/skills/repo-profile.md → Build & test → Single-suite filter. Where the two disagree, the profile wins and this block is the stale one; keep corrections there and re-summarise here rather than growing a second copy.

Running the Demo Application

cd FormCraft.DemoBlazorApp
dotnet run
# Navigate to https://localhost:5001 (or http://localhost:5000)

Build (build.cs)

CI runs build.cs, an Isotope build:

dotnet run build.cs                  # list the targets
dotnet run build.cs -- test          # restore, compile, test
dotnet run build.cs -- pack          # the same, then the NuGet packages
# `publish` sends them to nuget.org. Only the release workflow runs it.
# There is no changelog target: CHANGELOG.md is generated and owned by release-please.

High-Level Architecture

Solution Structure

FormCraft/                      # Core library (framework-agnostic)
├── Builders/                   # Fluent API builders
│   ├── FormBuilder.cs         # Main entry point
│   ├── FieldBuilder.cs        # Individual field configuration
│   └── FieldGroupBuilder.cs   # Field grouping and layout
├── Configuration/              # Configuration models
├── Rendering/                  # Rendering pipeline
│   ├── IFieldRenderer.cs      # Renderer contract
│   └── FieldRendererService.cs # Renderer registry
├── Validation/                 # Validation system
│   └── IFieldValidator.cs     # Validator contract
├── Security/                   # Security features (v2.0.0+)
│   ├── IEncryptionService.cs  # Field encryption
│   └── ICsrfTokenService.cs   # CSRF protection
└── Extensions/                 # Extension methods

FormCraft.ForMudBlazor/         # MudBlazor UI implementation
├── Renderers/                  # MudBlazor-specific renderers
└── Services/                   # UI framework services

FormCraft.DemoBlazorApp/        # Interactive demo application
FormCraft.UnitTests/            # Core library test suite (560+ tests)
FormCraft.ForMudBlazor.UnitTests/ # MudBlazor integration tests (47 tests)
build.cs                        # Isotope build; build/ holds its README and the version-tag rule

Target Frameworks

  • net8.0, net10.0 and net11.0 — built with the .NET 11 SDK. All three shipping projects (FormCraft, FormCraft.ForMudBlazor, FormCraft.ForFluentUI) declare <TargetFrameworks>net8.0;net10.0;net11.0</TargetFrameworks>; the test projects run on net10.0 and net11.0; the demo app is net10.0 only. ⛔ There is no net9.0 target — this file claimed one until #285. The csproj files are the authority here, so verify against them before re-adding a framework to this list; a demo page advertising net8.0 · net10.0 · net11.0 is correct, not stale.

Core Design Patterns

1. Fluent Builder Pattern (Primary Architecture)

The entire API is built around method chaining with immutable configuration:

FormBuilder<TModel>.Create()
    .AddField(x => x.Property, field => field.WithLabel("Name").Required())
    .AddFieldGroup(group => group.WithGroupName("Contact").WithColumns(2))
    .WithLayout(FormLayout.Grid)
    .WithSecurity(security => security.EncryptField(x => x.SSN).EnableCsrfProtection())
    .Build() // Returns immutable IFormConfiguration<TModel>

Key Builder Classes:

  • FormBuilder<TModel> - Root builder, entry point via .Create()
  • FieldBuilder<TModel, TValue> - Configures individual fields
  • FieldGroupBuilder<TModel> - Groups fields with layout options
  • SecurityBuilder<TModel> - Security features configuration (encryption, CSRF, rate limiting)

2. Strategy Pattern (Field Rendering)

Pluggable rendering system with type-based renderer selection:

public interface IFieldRenderer
{
    bool CanRender(Type fieldType, IFieldConfiguration<object, object> field);
    RenderFragment Render<TModel>(IFieldRenderContext<TModel> context);
}

Renderer Registration:

  • Default renderers registered in DI container
  • Custom renderers via .WithCustomRenderer()
  • Priority-based selection when multiple renderers match

3. Command Pattern (Validation)

Async validation with command pattern:

public interface IFieldValidator<TModel, TValue>
{
    Task<ValidationResult> ValidateAsync(TModel model, TValue value, IServiceProvider services);
}

Built-in Validators:

  • RequiredValidator<TModel, TValue>
  • CustomValidator<TModel, TValue>
  • AsyncValidator<TModel, TValue>
  • FluentValidation integration via DynamicFormValidator

4. Observer Pattern (Field Dependencies)

Reactive field updates based on dependencies:

.AddField(x => x.TotalPrice, field => field
    .DependsOn(x => x.Quantity, (model, quantity) => model.TotalPrice = quantity * model.Price)
    .VisibleWhen(model => model.Quantity > 0))

Dependency Types:

  • Value dependencies - Auto-calculate field values
  • Visibility dependencies - Show/hide fields conditionally

Conditional validation (e.g. "required only when Country is US") is not a DependsOn dependency — it is a custom IFieldValidator<TModel, TValue> that reads other properties directly off model in ValidateAsync(model, value, services); see RequiredWhenUsValidator in README.md's "Conditional fields" section.

5. Adapter Pattern (UI Framework Integration)

Framework-agnostic core with UI-specific adapters. The seam is FieldRendererBase plus precedence-ordered DI registration — there is no adapter interface. An adapter is just an assembly that registers its own IFieldRenderers; two of them ship (FormCraft.ForMudBlazor, FormCraft.ForFluentUI) and both were built on exactly this.

⛔ There used to be an IUIFrameworkAdapter documented here with a RenderField/RenderForm shape. That interface had neither method and — across 8 reference sites — not one consumer; it was deleted in #279 along with FrameworkAgnosticFieldRenderer and UIFrameworkConfiguration. Do not reintroduce it: a contributor who builds against it is building against something nothing calls.

A renderer names the component to render and says which fields it claims:

public class MyTextFieldRenderer : FieldRendererBase
{
    protected override Type ComponentType => typeof(MyTextFieldComponent<,>);   // closed over TModel/TValue

    public override bool CanRender(Type fieldType, IFieldConfiguration<object, object> field)
        => fieldType == typeof(string);
}

Registration order is the precedence rule, because IFieldRendererService picks the first renderer whose CanRender matches. Configuration-driven renderers (select, LOV, lookup, autocomplete, file upload) must therefore be registered before the generic type-based ones, or a string field carrying options ends up in the plain text renderer. AddFormCraft<Framework>() also strips core's built-in renderers — only those from the core assembly, so an application's own custom renderers survive and keep precedence.

Components derive from FieldComponentBase<TModel, TValue> (core), which supplies Context, Value/ValueChanged, Label, IsRequired and the rest; each adapter adds its own presentation layer on top (MudBlazorFieldComponentBase, FluentUIFieldComponentBase). Shared, UI-agnostic adapter machinery lives in core so both adapters read one implementation — NativeRequired.Resolve, .WithNativeRequired(...), DynamicFormValidator<TModel> and AdapterRegistration.EnsureSingleAdapter (#279).

One adapter per container. Both AddFormCraftMudBlazor() and AddFormCraftFluentUI() call AdapterRegistration.EnsureSingleAdapter, so whichever runs second throws — the rule is symmetric because it lives in core rather than in one of the two packages that need it.

Key Abstractions and Extension Points

Configuration Abstractions

  • IFormConfiguration<TModel> - Complete immutable form configuration
  • IFieldConfiguration<TModel, TValue> - Individual field settings
  • IFieldGroupConfiguration<TModel> - Group layout and settings
  • IFormSecurity - Security configuration

Rendering Pipeline

  1. IFieldRendererService - Central rendering coordinator
  2. IFieldRenderContext<TModel> - Rendering context with model and callbacks
  3. ICustomFieldRenderer<TValue> - Base for custom renderers
  4. CustomFieldRendererBase<T> - Simplified custom renderer base class

Validation System

  • IFieldValidator<TModel, TValue> - Core validation contract
  • ValidationResult - Validation outcome (IsValid, ErrorMessage)
  • DynamicFormValidator - FluentValidation integration component
  • Validators can be sync or async

Security Features (v2.0.0+)

.WithSecurity(security => security
    .EncryptField(x => x.SSN)
    .EncryptField(x => x.CreditCard)
    .EnableCsrfProtection()
    .WithRateLimit(5, TimeSpan.FromMinutes(1))
    .EnableAuditLogging(cfg => cfg.LogFieldChanges = true))

Important Conventions

Fluent API Design Rules

  • All builder methods return this for chaining
  • Configuration is immutable after .Build()
  • Method naming: Add* (add items), With* (configure), Enable* (features)
  • No side effects in builder methods

Type Safety and Expression Trees

  • Heavy use of generics for compile-time safety
  • Expression trees for property binding: x => x.Property
  • Strong typing throughout: FieldBuilder<TModel, TValue>
  • No magic strings for property names

Validation Behavior

  • The convention governs browser constraint validation, not accessibility annotations (#199). Those are different things, and conflating them is what left required fields silent to screen readers. Required() routes validation server-side and the browser runs none — but a required field must still be identified, which is WCAG 2.1 3.3.2 (Level A)
  • Required() adds validation but NOT the HTML5 required attribute — the convention in its literal form, restored by #263. It was amended between #199 and #263 only because MudBlazor 9.8.0 fused the two: MudInput splatted UserAttributes and then wrote its own required and aria-required afterwards, both off one Required flag, so last-write-wins meant a caller could never supply the annotation on its own. MudBlazor#13613 moved the ARIA writes above the splat and left required below it; shipped in 9.9.0
  • Required() therefore now contributes aria-required="true" through UserAttributes and leaves MudBlazor's Required parameter alone. ⛔ Do not "simplify" this back to setting Required — that reintroduces the HTML5 attribute this convention forbids. And do not drop the annotation either: that is #190, and it is a Level A failure. Both halves are pinned by AriaRequiredTests
  • ⚠️ The visible asterisk is gone for a plain .Required(...) field, and that is a decision, not a regression to fix. MudBlazor draws it from the same Required parameter as the HTML5 attribute, and #13613 did not separate those two. .WithNativeRequired() is the documented way back to native semantics — asterisk and HTML5 attribute together
  • 🔒 Version floor: MudBlazor ≥ 9.9.0. On anything older, 9 of the 35 AriaRequiredTests fail (measured by reverting the pin). Do not lower Directory.Packages.props below it
  • Browser validation disabled via a novalidate attribute rendered on the form by FormCraftComponent (#206). It is a real attribute in the markup, so it applies during prerender/SSR, targets this component's own form rather than the first one on the page, and needs no JavaScript. ⛔ Do not reintroduce the JSRuntime.InvokeVoidAsync("eval", …) version: it marked document.querySelector('form') — the wrong form on any page with another form above it — never ran on the server pass, failed silently, and was blocked outright by a strict CSP
  • All validation through FluentValidation
  • Validation messages from server, not browser
  • MudBlazor components announce aria-required for a .Required(...) field on every field type that can carry it: text, numeric, date, select, multi-select, autocomplete, lookup, LOV and boolean. ⛔ Keep it uniform when adding a field type — a required field that says nothing is a Level A failure, and one that says aria-required="false" states the opposite of the truth. The value comes from MudBlazorFieldComponentBase.AriaRequired; bind it alongside Required in the new component's .razor
  • Every field type now takes the UserAttributes route that checkboxes always did. Since 9.9.0 a caller-supplied aria-required wins on MudInput-based fields too, so there is one mechanism rather than two. ⚠️ AriaRequired returns "true"/"false" and never null: a null component parameter is still captured into UserAttributes as a present key, and Blazor deletes an attribute whose last write is null — returning null for optional fields drops aria-required entirely instead of leaving it "false" (measured; it turned five assertions red)
  • File upload is covered too, but NOT via Required on MudFileUpload (#262). Its <input type="file"> carries tabindex="-1" and stays hidden behind a custom drop zone (unhidden as a transparent mud-file-upload-dragover overlay only while a drag is over the zone), so annotating that input satisfies a DOM assertion while reaching no user who navigates by focus. Both upload components mark the requirement on two reachable channels instead: a visible * in the field's own <MudText> label, and aria-describedby on the Browse MudButton pointing at a mud-sr-only description. The rule lives in MudBlazorFileUploadComponentBase and the markup in FileUploadRequiredMarker/FileUploadRequiredHint, so the single- and multiple-file components cannot drift — centralising only the values still leaves two copies of the markup
  • ⛔ Do not "also bind Required" on MudFileUpload as belt-and-braces. It was tried under #262 and reverted with a measurement: MudFormComponent raises its own RequiredError once the flag is set, and with no cascaded EditContext — a standalone IFieldRendererService.RenderField, which this suite exercises — clearing a required upload rendered mud-input-error plus helper text reading "Required", MudBlazor's wording rather than the developer's. Pinned by AriaRequiredTests.Clearing_A_Standalone_Required_Upload_Should_Not_Surface_MudBlazors_Own_Error. Note MudFileUpload.Error/ErrorText stay clean because FormCraft passes ErrorText="" as a parameter while MudBlazor writes its own internal state — so assert the rendered DOM, not those properties, or the test proves nothing
  • The upload asterisk is a text node, not MudBlazor's CSS ::after. MudBlazor's only rule is .mud-input-control.mud-input-required > .mud-input-control-input-container > .mud-input-label::after, which never matches FormCraft's span. So the marker carries its own formcraft-required-marker class — select and restyle that, and don't tell users to restyle .mud-input-required for upload fields
  • The hint id must stay unique per rendered instance. formcraft-{FieldName}-required-{guid8}: the field name alone is not unique in a document, because item fields render through these very components since #203 (one hint per row), two forms over one model collide the same way, and two nested fields can share a member name. A test using two different fields cannot catch this — different names never collide; the real case is the same field rendered twice
  • {FieldName} in that template is the CSS-sanitized form, not the raw one, since #449. A nested binding's FieldName is a dotted path ("Billing.Amount", #437/#448), and an unescaped . inside an HTML id is a valid character but the CSS class-selector delimiter — #formcraft-help- Billing.Amount parses as "id formcraft-help-Billing and class Amount". IdSanitizer.ToCssSafeId (FormCraft/Forms/Rendering/IdSanitizer.cs) maps . → - before interpolation, in the one place every id builder that embeds FieldName routes through (FieldHelpText.IdFor, both adapters' upload RequiredDescriptionId) — add a new one through it rather than a fourth copy of the escape
  • MudFileUpload renders its own file list independently of CustomContent — CustomContent replaces the drop target, not the file list, and the two are gated by separate parameters (measured by decompiling MudBlazor 9.10.0's MudFileUpload.razor.cs, #338). Left alone, that meant a selected file appeared twice in the multiple-file upload — once as FormCraft's own chip under .mud-file-upload-custom-content, once as MudBlazor's own under .mud-file-upload-filelist — each with its own close button, and only FormCraft's routed through RemoveFile and therefore through #318's focus-restore. The single-file component duplicated too, but asymmetrically: its own chip carries no OnClose at all, so MudBlazor's was the only working close button it had. Both components now set MudFileUpload<T>.SelectedTemplate to an empty template (MudBlazorFileUploadComponentBase.SuppressBuiltInFileList) — any non-null SelectedTemplate takes MudBlazor's SelectedTemplate(...) branch instead of its default chip list, so an empty one suppresses that list entirely while leaving CustomContent untouched. ⛔ Don't reach for ShowPreview here: it is FormCraft's own unrelated code-behind property (drives the drop zone's height), not a MudFileUpload parameter, and setting it does nothing to the duplicate list.
  • A cleared multiple-file upload holds an empty list, not null (#319). MudBlazorMultipleFileUploadComponent binds Files/FilesChanged one-way, with an explicit OnFilesChanged handler, instead of @bind-Files — because @bind-Files made MudBlazor a second writer of CurrentValue: ClearAsync() set the field's own empty list, then MudFileUpload.ClearAsync()'s own FilesChanged(null) echo landed on the two-way binding and overwrote it with null, so the field notified twice and ended up holding null instead of empty. One-way binding plus the handler normalising null to an empty list makes OnFilesChanged the only writer left, mirroring the single-file component's Files/OnFileChanged shape. Pinned by FileUploadNotificationTests.
  • A control that unmounts or disables itself on activation must move focus deliberately — otherwise the element the keyboard user is standing on stops being focusable, focus falls to <body>, and the next Tab restarts from the top of the document (WCAG 2.1 2.4.3 Focus Order, Level A). Both variants count: an @if over the value the handler mutates (upload Clear/chip close, collection delete/Add), and a Disabled binding the handler can make true (collection move up/down at the ends — browsers drop focus from a newly-disabled element). The swallow-safe catch list lives once, in core — FormCraft.FocusRestore.SafelyAsync (#337, extracted from FormCraft.ForMudBlazor's original FocusRestore under #281/#318) — and each adapter calls it through its own thin, UI-typed wrapper: FormCraft.ForMudBlazor.FocusRestore.FocusSafelyAsync(MudBaseButton?/ElementReference) and FormCraft.ForFluentUI.FocusRestore.FocusSafelyAsync(ElementReference). The collection field's four controls (add, delete, move up, move down) carry this guarantee in both adapters; the upload Clear/chip-close controls have it only in MudBlazor — FormCraft.ForFluentUI's file-upload components render no self-unmounting or disabling control at all as of this issue (#385), so the WCAG 2.4.3 gap MudBlazor had before #281/#318 does not currently exist there; a future removal control must route through FormCraft.ForFluentUI.FocusRestore from the start. Targets, MudBlazor upload: Clear and chip-close → the field's Browse button, because it carries #262's aria-describedby so the requirement is announced exactly when removal makes the field unsatisfied. Targets, either adapter's collection field: row delete → the delete control taking the vacated slot, else the previous row's, else Add, else the collection header; Add (only on the click that reaches MaxItems) → the new row's header, not its delete control (Enter there would undo the add) and not a field (they render through IFieldRendererService and expose no reference); a move → the same row's still-enabled move control, so focus follows the item rather than sitting on an index that now controls a different one. ⚠️ Only the core catch list is shared — each @ref and call site is written per component, and the null guard makes a dropped @ref silent, so a new control needs its own focus test. ⛔ Don't narrow the catch list: the action has already succeeded, so a failed focus must stay a no-op. JSException is the likely one — domWrapper.focus raises it for an element that has left the DOM, which OnValueChanged can cause between the mutation and the awaited interop call. Losing that catch escapes the click handler and tears down a Server circuit; A_Failing_Focus_Call_Should_Not_Break_A_*_Clear and FormCraft.UnitTests/Rendering/FocusRestoreTests.cs pin it — the core suite exercises all five exception types, while each adapter's own FocusRestoreTests only smoke-tests JSException at the wrapper level
  • ⛔ A @ref on a component is captured once, when that component is created — it is NOT re-run on later renders. So a per-index reference store must not be cleared each render to prune stale entries: doing so permanently loses the references for rows that were merely retained, and every subsequent focus falls through to the next target in the chain (measured under #318 — removals silently focused Add). Let the entries outlive their rows and decide from what is rendered now instead: bounds-check the index against Items.Count and re-evaluate the markup's own gate (CanRemove && !HasReachedMin), since reaching MinItems unmounts every row's delete control at once. Element references (@ref on plain HTML) are re-captured each render — the two behave differently, which is why the row header fallback is an ElementReference in MudBlazor's CollectionFieldComponent. The Fluent UI adapter's FluentUICollectionFieldComponent sidesteps this hazard differently for its two kinds of target: FluentButton (the pinned v5 RC) exposes no focus API and no public ElementReference of its own — confirmed by decompiling the installed assembly, it neither declares FocusAsync() nor implements IFluentComponentElementBase — so its collection header and per-row header fallbacks stay plain wrapping <div>s with their own @ref, re-captured every render like any other element reference (no component-typed target to go stale there); its four FluentButton controls (Add, Remove, Move up, Move down) are focused by a deterministically-computed DOM id through a small JS module instead (#383) — a throwaway bUnit probe found FluentButton renders as a native custom element (<fluent-button>) with no static CSS class list, so there is nothing for Blazor's own ElementReference machinery to capture on it at all; its Id parameter renders straight through to the element's id attribute, which document.getElementById reaches directly, no longer through a wrapping <span>.
  • Move focus from OnAfterRenderAsync, not from the handler. The row you are aiming at may not exist, or may not be at that index, until the next render batch is applied — reading the captures inside the handler hands back the pre-action state. Set a pending-index field, act on it after the render (_focusAfterRemovalFrom / _focusRowAfterRender in CollectionFieldComponent and, identically, in FluentUICollectionFieldComponent)
  • Asserting focus in bUnit: assert the interop call, not DOM state. bUnit models no real focus. ElementReference.FocusAsync() records Blazor._internal.domWrapper.focus with the target ElementReference as Arguments[0] (measured on bUnit 2.9.0 / MudBlazor 9.8.0, and again on bUnit 2.9.0 / Fluent UI Blazor 5.0.0-rc.5 under #337). MudBlazor's MudButton exposes no public ElementReference — it lives in a private MudBaseButton._elementReference — and bUnit renders blazor:elementReference empty, so to say which button was focused, learn its id through the public API: call FocusAsync() on the candidate and read the id back off the recording (the id survives the clear re-render). ⛔ Don't reflect into MudBlazor's private field; it breaks on any patch release. Fluent has no such button-level API to call in the first place (see above), and since #383 it asserts its two kinds of focus target differently too. The header/row-header ElementReference fields are internal, reachable from the test project through FormCraft.ForFluentUI.csproj's InternalsVisibleTo, so a test skips the "focus it to learn its id" indirection and compares LastFocusedElementId() straight against the field's own .Id. The four FluentButton controls are focused by DOM id through a JS module instead: invoking a method on the IJSObjectReference bUnit's Loose-mode "import" auto-mock returns records into the same JSInterop.Invocations list under the module's own function name ("focusById"), so a test compares LastFocusedElementIdViaModule() against the component's own internal *TargetId accessor. MudBlazor's helpers live once on FormCraft.ForMudBlazor.UnitTests.TestSupport.FocusAssertingTestBase — FocusCount(), LastFocusedElementId(), LearnElementIdAsync(...) (takes MudBaseButton, so it covers MudIconButton too) and FailTheFocusInterop(); Fluent's own FormCraft.ForFluentUI.UnitTests.TestSupport.FocusAssertingTestBase carries FocusCount(), LastFocusedElementId() and FailTheFocusInterop() for the header/row-header mechanism, plus FocusByIdCount() and LastFocusedElementIdViaModule() (#383) for the four-button mechanism. See FileUploadClearFocusTests, CollectionFocusTests and FocusRestoreTests in each adapter's test project.
  • Loose JSInterop makes focus always succeed, so a "does not throw" test proves nothing unless it makes the call fail — use FailTheFocusInterop(). Without it the catch block has zero coverage, which is exactly how a missing catch (JSException) shipped under #281. MudBlazorTestBase and FluentUITestBase both run Loose by default, so this applies in either adapter's suite.

Testing Patterns

// Arrange-Act-Assert pattern with Shouldly assertions
[Fact]
public void MethodName_Should_ExpectedBehavior_When_Condition()
{
    // Arrange
    var builder = FormBuilder<TestModel>.Create();

    // Act
    var result = builder.AddField(x => x.Name);

    // Assert
    result.ShouldBeSameAs(builder);
}

MudBlazor Component Testing (bUnit)

// Use MudBlazorTestBase for component tests
public class MyTests : MudBlazorTestBase  // Inherits from BunitContext
{
    [Fact]
    public void Component_Should_Render_Field()
    {
        var model = new TestModel();
        var config = FormBuilder<TestModel>.Create()
            .AddField(x => x.Name, field => field.WithLabel("Name"))
            .Build();

        var component = Render<FormCraftComponent<TestModel>>(parameters => parameters
            .Add(p => p.Model, model)
            .Add(p => p.Configuration, config));

        component.FindComponent<MudTextField<string>>().ShouldNotBeNull();
    }
}

Common Development Patterns

Adding a Custom Field Renderer

// 1. Create renderer class
public class ColorPickerRenderer : CustomFieldRendererBase<string>
{
    public override RenderFragment Render(IFieldRenderContext context)
    {
        return builder => {
            builder.OpenComponent<MudColorPicker>(0);
            builder.AddAttribute(1, "Value", GetValue(context));
            builder.AddAttribute(2, "ValueChanged", EventCallback.Factory.Create<string>(this, v => SetValue(context, v)));
            builder.CloseComponent();
        };
    }
}

// 2. Register it in DI if it needs constructor-injected dependencies
// (FieldRendererService resolves CustomRendererType via IServiceProvider.GetService)
services.AddScoped<ColorPickerRenderer>();

// 3. Attach it to a field
.WithCustomRenderer<ColorPickerRenderer>()

Creating Reusable Field Configurations

public static class FormExtensions
{
    public static FormBuilder<TModel> AddEmailField<TModel>(
        this FormBuilder<TModel> builder,
        Expression<Func<TModel, string>> propertyExpression)
        where TModel : new()
    {
        return builder.AddField(propertyExpression, field => field
            .WithLabel("Email Address")
            .WithPlaceholder("user@example.com")
            .WithInputType("email")
            .Required("Email is required")
            .WithValidator(new EmailValidator<TModel>()));
    }
}

Implementing Field Dependencies

// Conditional visibility
.AddField(x => x.State, field => field
    .VisibleWhen(model => model.Country == "USA"))

// Calculated values (chain one .DependsOn(...) call per dependency)
.AddField(x => x.Total, field => field
    .DependsOn(x => x.Quantity, (model, quantity) =>
        model.Total = quantity * model.Price * (1 + model.TaxRate))
    .DependsOn(x => x.Price, (model, price) =>
        model.Total = model.Quantity * price * (1 + model.TaxRate))
    .DependsOn(x => x.TaxRate, (model, taxRate) =>
        model.Total = model.Quantity * model.Price * (1 + taxRate))
    .ReadOnly())

Form Templates

// Use predefined templates
var form = FormTemplates.LoginForm<LoginModel>();
var form = FormTemplates.RegistrationForm<UserModel>();

// Create custom template — FormCraft has no built-in wizard/multi-step layout.
// The built-in templates above return a built IFormConfiguration<T>; your own
// "template" can be any static method — here, one returning a configured FormBuilder<T>
public static class MyTemplates
{
    public static FormBuilder<T> CreateGridForm<T>() where T : new()
    {
        return FormBuilder<T>.Create()
            .WithLayout(FormLayout.Grid);
    }
}

Advanced Features

Security Configuration

.WithSecurity(security => security
    // Field-level encryption
    .EncryptField(x => x.SSN)
    .EncryptField(x => x.CreditCard)
    
    // CSRF protection
    .EnableCsrfProtection()
    
    // Rate limiting
    .WithRateLimit(5, TimeSpan.FromMinutes(1))
    
    // Audit logging — the Action<AuditLogConfiguration> callback is the only
    // fluent audit-logging configuration surface; swapping the logger
    // implementation itself is a DI concern (IAuditLogService), not a builder method
    .EnableAuditLogging(cfg => cfg.LogFieldChanges = true))

Field Groups with Layouts

.AddFieldGroup(group => group
    .WithGroupName("Contact Information")
    .WithColumns(2)
    .ShowInCard(elevation: 2)
    .AddField(x => x.Email)
    .AddField(x => x.Phone)
    .AddField(x => x.Address))

Async Operations

// Async validation — a bare Func<TValue, Task<bool>> plus a separate error message,
// not a ValidationResult-returning function
.WithAsyncValidator(
    async value => await apiService.CheckUniqueAsync(value),
    "Value must be unique")

// FormCraft has no separate async-value-provider method — a value computed from an
// async source is set inside a DependsOn async callback instead
.DependsOn(x => x.Id, async (model, id) =>
    model.DefaultValue = await apiService.GetDefaultValueAsync(id))

Versioning and Release Process

  • Versioning: MinVer derives the version from the git tag. No file records it — do not add a <Version> element, MinVer's targets override it.
  • Release: owned by release-please. It keeps a release PR open against dev; merging that PR tags vX.Y.Z, creates the GitHub Release, and publishes both packages in the same workflow run. Never tag by hand — no workflow is triggered by on: push: tags any more, so a hand-pushed tag silently produces nothing.
  • Changelog: CHANGELOG.md is generated by release-please. Never hand-edit it, and never add a generator for it — a second writer would rewrite the file out from under the open release PR. (git-cliff and cliff.toml were removed for exactly this reason.)
  • Commits: Follow conventional commits (feat:, fix:, docs:, test:, refactor:). PRs are squash-merged, so the PR title is the commit release-please parses — pr-title-lint.yml enforces it.
  • CI/CD: GitHub Actions. ci.yml and continuous.yml build/test/pack only; release-please.yml is the only workflow that publishes, via NuGet Trusted Publishing (OIDC).