This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
# 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 # Windowsdotnet 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 onlyEnforceCodeStyleInBuildis deliberately NOT set, soIDE*analyzers do not run duringdotnet build. That is why.editorconfig'swarningseverities never metTreatWarningsAsErrorsand 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 breakdotnet buildmid-edit and every incremental build would pay for the analyzer pass. TheFormatCI step is where regression is caught.⚠️ dotnet formatcan corrupt multi-targeted files when it applies fixes.FormCraftisnet8.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.csfile — code that does not compile (measured in #301 onFieldRendererBase.cs). Verify mode never writes, so CI is safe. The guard isFormCraft.UnitTests/Ci/ConflictMarkerTests(#347) — it failsdotnet testif a tracked.csfile carries a marker, so a corrupted file cannot reachdevunnoticed.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.⚠️ Onedotnet formatrun does not always reach a fixpoint. Measured in #301: after formatting afield-keyword property, verify still reported threeWHITESPACEdiagnostics on it, and a second run cleared them. If theformattarget fails right after you formatted, run the formatter again before assuming the gate is wrong.IDE0032now rewrites a private backing field into C# 14'sfieldkeyword. Value-identical, but it silently deletes the XML docs that lived on the field — which onMudBlazorFileUploadComponentBase.RequiredDescriptionIdwere 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.
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.GitignoreTestsFilters: --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].
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.
- One aggregate summary.
dotnet testprints a singleTest run summary: <verdict>block naming every assembly it ran, thentotal:/failed:/succeeded:/skipped:on separate lines — the verdict and the count never share a line. $?is only meaningful unpiped.| tail/| grepreplaces it with the pipe's0.- Filter matching nothing →
Zero tests ran,total: 0, exit8, on both paths. A solution-wide-- --filter-class …is this case for two of the three assemblies: aggregateFailed!,error: 2, exit8— hence "always name the.csproj". - Mistyped flag → exit
5. Throughdotnet testit looks like an empty filter (Zero tests ran,error: 1, noUnknown optiontext), so the exit code — 5 vs 8 — is the only tell. The direct host printsUnknown option '--…'plus the full--helpand no summary line at all (sogrep '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.
cd FormCraft.DemoBlazorApp
dotnet run
# Navigate to https://localhost:5001 (or http://localhost:5000)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.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
- 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 onnet10.0andnet11.0; the demo app isnet10.0only. ⛔ 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 advertisingnet8.0 · net10.0 · net11.0is correct, not stale.
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 fieldsFieldGroupBuilder<TModel>- Groups fields with layout optionsSecurityBuilder<TModel>- Security features configuration (encryption, CSRF, rate limiting)
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
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
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.
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.
IFormConfiguration<TModel>- Complete immutable form configurationIFieldConfiguration<TModel, TValue>- Individual field settingsIFieldGroupConfiguration<TModel>- Group layout and settingsIFormSecurity- Security configuration
IFieldRendererService- Central rendering coordinatorIFieldRenderContext<TModel>- Rendering context with model and callbacksICustomFieldRenderer<TValue>- Base for custom renderersCustomFieldRendererBase<T>- Simplified custom renderer base class
IFieldValidator<TModel, TValue>- Core validation contractValidationResult- Validation outcome (IsValid, ErrorMessage)DynamicFormValidator- FluentValidation integration component- Validators can be sync or async
.WithSecurity(security => security
.EncryptField(x => x.SSN)
.EncryptField(x => x.CreditCard)
.EnableCsrfProtection()
.WithRateLimit(5, TimeSpan.FromMinutes(1))
.EnableAuditLogging(cfg => cfg.LogFieldChanges = true))- All builder methods return
thisfor chaining - Configuration is immutable after
.Build() - Method naming:
Add*(add items),With*(configure),Enable*(features) - No side effects in builder methods
- 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
- 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 HTML5requiredattribute — 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:MudInputsplattedUserAttributesand then wrote its ownrequiredandaria-requiredafterwards, both off oneRequiredflag, 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 leftrequiredbelow it; shipped in 9.9.0Required()therefore now contributesaria-required="true"throughUserAttributesand leaves MudBlazor'sRequiredparameter alone. ⛔ Do not "simplify" this back to settingRequired— 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 byAriaRequiredTests⚠️ 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 sameRequiredparameter 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
AriaRequiredTestsfail (measured by reverting the pin). Do not lowerDirectory.Packages.propsbelow it - Browser validation disabled via a
novalidateattribute rendered on the form byFormCraftComponent(#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 theJSRuntime.InvokeVoidAsync("eval", …)version: it markeddocument.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-requiredfor 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 saysaria-required="false"states the opposite of the truth. The value comes fromMudBlazorFieldComponentBase.AriaRequired; bind it alongsideRequiredin the new component's.razor - Every field type now takes the
UserAttributesroute that checkboxes always did. Since 9.9.0 a caller-suppliedaria-requiredwins onMudInput-based fields too, so there is one mechanism rather than two.⚠️ AriaRequiredreturns"true"/"false"and nevernull: a null component parameter is still captured intoUserAttributesas a present key, and Blazor deletes an attribute whose last write is null — returningnullfor optional fields dropsaria-requiredentirely instead of leaving it"false"(measured; it turned five assertions red) - File upload is covered too, but NOT via
RequiredonMudFileUpload(#262). Its<input type="file">carriestabindex="-1"and stays hidden behind a custom drop zone (unhidden as a transparentmud-file-upload-dragoveroverlay 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, andaria-describedbyon the BrowseMudButtonpointing at amud-sr-onlydescription. The rule lives inMudBlazorFileUploadComponentBaseand the markup inFileUploadRequiredMarker/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" onMudFileUploadas belt-and-braces. It was tried under #262 and reverted with a measurement:MudFormComponentraises its ownRequiredErroronce the flag is set, and with no cascadedEditContext— a standaloneIFieldRendererService.RenderField, which this suite exercises — clearing a required upload renderedmud-input-errorplus helper text reading"Required", MudBlazor's wording rather than the developer's. Pinned byAriaRequiredTests.Clearing_A_Standalone_Required_Upload_Should_Not_Surface_MudBlazors_Own_Error. NoteMudFileUpload.Error/ErrorTextstay clean because FormCraft passesErrorText=""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'sspan. So the marker carries its ownformcraft-required-markerclass — select and restyle that, and don't tell users to restyle.mud-input-requiredfor 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'sFieldNameis 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.Amountparses as "idformcraft-help-Billingand classAmount".IdSanitizer.ToCssSafeId(FormCraft/Forms/Rendering/IdSanitizer.cs) maps.→-before interpolation, in the one place every id builder that embedsFieldNameroutes through (FieldHelpText.IdFor, both adapters' uploadRequiredDescriptionId) — add a new one through it rather than a fourth copy of the escapeMudFileUploadrenders its own file list independently ofCustomContent—CustomContentreplaces the drop target, not the file list, and the two are gated by separate parameters (measured by decompiling MudBlazor 9.10.0'sMudFileUpload.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 throughRemoveFileand therefore through #318's focus-restore. The single-file component duplicated too, but asymmetrically: its own chip carries noOnCloseat all, so MudBlazor's was the only working close button it had. Both components now setMudFileUpload<T>.SelectedTemplateto an empty template (MudBlazorFileUploadComponentBase.SuppressBuiltInFileList) — any non-nullSelectedTemplatetakes MudBlazor'sSelectedTemplate(...)branch instead of its default chip list, so an empty one suppresses that list entirely while leavingCustomContentuntouched. ⛔ Don't reach forShowPreviewhere: it is FormCraft's own unrelated code-behind property (drives the drop zone's height), not aMudFileUploadparameter, and setting it does nothing to the duplicate list.- A cleared multiple-file upload holds an empty list, not
null(#319).MudBlazorMultipleFileUploadComponentbindsFiles/FilesChangedone-way, with an explicitOnFilesChangedhandler, instead of@bind-Files— because@bind-Filesmade MudBlazor a second writer ofCurrentValue:ClearAsync()set the field's own empty list, thenMudFileUpload.ClearAsync()'s ownFilesChanged(null)echo landed on the two-way binding and overwrote it withnull, so the field notified twice and ended up holdingnullinstead of empty. One-way binding plus the handler normalisingnullto an empty list makesOnFilesChangedthe only writer left, mirroring the single-file component'sFiles/OnFileChangedshape. Pinned byFileUploadNotificationTests. - 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@ifover the value the handler mutates (upload Clear/chip close, collection delete/Add), and aDisabledbinding 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 fromFormCraft.ForMudBlazor's originalFocusRestoreunder #281/#318) — and each adapter calls it through its own thin, UI-typed wrapper:FormCraft.ForMudBlazor.FocusRestore.FocusSafelyAsync(MudBaseButton?/ElementReference)andFormCraft.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 throughFormCraft.ForFluentUI.FocusRestorefrom the start. Targets, MudBlazor upload: Clear and chip-close → the field's Browse button, because it carries #262'saria-describedbyso 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 reachesMaxItems) → the new row's header, not its delete control (Enter there would undo the add) and not a field (they render throughIFieldRendererServiceand 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@refand call site is written per component, and the null guard makes a dropped@refsilent, 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.JSExceptionis the likely one —domWrapper.focusraises it for an element that has left the DOM, whichOnValueChangedcan 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_*_ClearandFormCraft.UnitTests/Rendering/FocusRestoreTests.cspin it — the core suite exercises all five exception types, while each adapter's ownFocusRestoreTestsonly smoke-tests JSException at the wrapper level - ⛔ A
@refon 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 againstItems.Countand re-evaluate the markup's own gate (CanRemove && !HasReachedMin), since reachingMinItemsunmounts every row's delete control at once. Element references (@refon plain HTML) are re-captured each render — the two behave differently, which is why the row header fallback is anElementReferencein MudBlazor'sCollectionFieldComponent. The Fluent UI adapter'sFluentUICollectionFieldComponentsidesteps this hazard differently for its two kinds of target:FluentButton(the pinned v5 RC) exposes no focus API and no publicElementReferenceof its own — confirmed by decompiling the installed assembly, it neither declaresFocusAsync()nor implementsIFluentComponentElementBase— 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 fourFluentButtoncontrols (Add, Remove, Move up, Move down) are focused by a deterministically-computed DOMidthrough a small JS module instead (#383) — a throwaway bUnit probe foundFluentButtonrenders as a native custom element (<fluent-button>) with no static CSS class list, so there is nothing for Blazor's ownElementReferencemachinery to capture on it at all; itsIdparameter renders straight through to the element'sidattribute, whichdocument.getElementByIdreaches 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/_focusRowAfterRenderinCollectionFieldComponentand, identically, inFluentUICollectionFieldComponent) - Asserting focus in bUnit: assert the interop call, not DOM state. bUnit models no real focus.
ElementReference.FocusAsync()recordsBlazor._internal.domWrapper.focuswith the targetElementReferenceasArguments[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'sMudButtonexposes no publicElementReference— it lives in a privateMudBaseButton._elementReference— and bUnit rendersblazor:elementReferenceempty, so to say which button was focused, learn its id through the public API: callFocusAsync()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-headerElementReferencefields areinternal, reachable from the test project throughFormCraft.ForFluentUI.csproj'sInternalsVisibleTo, so a test skips the "focus it to learn its id" indirection and comparesLastFocusedElementId()straight against the field's own.Id. The fourFluentButtoncontrols are focused by DOM id through a JS module instead: invoking a method on theIJSObjectReferencebUnit's Loose-mode"import"auto-mock returns records into the sameJSInterop.Invocationslist under the module's own function name ("focusById"), so a test comparesLastFocusedElementIdViaModule()against the component's owninternal *TargetIdaccessor. MudBlazor's helpers live once onFormCraft.ForMudBlazor.UnitTests.TestSupport.FocusAssertingTestBase—FocusCount(),LastFocusedElementId(),LearnElementIdAsync(...)(takesMudBaseButton, so it coversMudIconButtontoo) andFailTheFocusInterop(); Fluent's ownFormCraft.ForFluentUI.UnitTests.TestSupport.FocusAssertingTestBasecarriesFocusCount(),LastFocusedElementId()andFailTheFocusInterop()for the header/row-header mechanism, plusFocusByIdCount()andLastFocusedElementIdViaModule()(#383) for the four-button mechanism. SeeFileUploadClearFocusTests,CollectionFocusTestsandFocusRestoreTestsin each adapter's test project. LooseJSInterop makes focus always succeed, so a "does not throw" test proves nothing unless it makes the call fail — useFailTheFocusInterop(). Without it the catch block has zero coverage, which is exactly how a missingcatch (JSException)shipped under #281.MudBlazorTestBaseandFluentUITestBaseboth runLooseby default, so this applies in either adapter's suite.
// 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);
}// 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();
}
}// 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>()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>()));
}
}// 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())// 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);
}
}.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)).AddFieldGroup(group => group
.WithGroupName("Contact Information")
.WithColumns(2)
.ShowInCard(elevation: 2)
.AddField(x => x.Email)
.AddField(x => x.Phone)
.AddField(x => x.Address))// 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: 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 tagsvX.Y.Z, creates the GitHub Release, and publishes both packages in the same workflow run. Never tag by hand — no workflow is triggered byon: push: tagsany more, so a hand-pushed tag silently produces nothing. - Changelog:
CHANGELOG.mdis 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 andcliff.tomlwere 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.ymlenforces it. - CI/CD: GitHub Actions.
ci.ymlandcontinuous.ymlbuild/test/pack only;release-please.ymlis the only workflow that publishes, via NuGet Trusted Publishing (OIDC).