6.2.8.2. FormVM¶
6.2.8.2.1. When To Use It¶
Use FormVM<TM> when the user edits a working copy, then either approves the
changes or denies them and reverts to the last snapshot. This is the right
primitive for editors, settings forms, CRUD dialogs, and other explicit
edit-save-cancel workflows.
6.2.8.2.2. Shape And Ownership¶
FormVM owns a live Model, a Snapshot, dirty tracking, validation state,
and approve/deny commands. It is not a leaf container and it is not a subclass
of ComponentVM; consumers typically compose it inside another VM that exposes
the host-specific editor surface.
Important members:
ModelplusSetModel(...)SnapshotIsDirtyErrors,IsValid,FieldError(...)ApproveCommand,ApproveAsync(),ApproveErrorsDenyCommand- optional builder
resetOnApproved/ResetOnApproved/reset_on_approved
Validation keys are unrestricted field names: every string, including the empty
string and JavaScript prototype names such as __proto__, constructor, or
toString, is an ordinary key. A field without an error reads as absent
(undefined, null, None, or nil), and Errors returns a fresh snapshot
whose keys are all own entries.
6.2.8.2.3. Lifecycle And Messaging¶
Construction captures the initial snapshot. After that:
- real model mutations recompute
IsDirty - validation re-runs on construct, set-model, and deny
- deny restores from the snapshot
- approve persists, advances the snapshot, and publishes
OnApproved - only one approval runs at a time; another approve while one is in flight does nothing
- when configured, reset-after-approve derives a new pristine model from the
captured persisted value before
OnApprovedfires - fire-and-forget approve failures surface on
ApproveErrors
Field validators run first. The model validator then runs and can add, replace,
or clear field errors: a null/none/nil value removes an entry, and an omitted
field keeps it. Rust alone accepts several model validators and runs them in
registration order. In Rust, the string-map with_model_validator /
model_validator forms can only add or replace; use
with_clearing_model_validator / clearing_model_validator, which return
BTreeMap<String, Option<String>>, to clear.
Repeated disposal completes the owned channels and commands at most once while preserving the form's inert post-dispose behavior. See the Disposal Contract.
Teardown is exception-resilient: a raising completion observer or owned disposable does not stop the remaining channels and commands from completing and disposing. Throwing flavors rethrow the first failure after every step has run. rxjs reports observer errors asynchronously, and Combine observers cannot throw.
In C# and Python, a teardown deferred until an in-progress set-model or deny finishes never replaces an error that mutation is already raising.
SetModel / set_model and deny are failure-atomic (spec chapter 20 §5.4,
ADR-0144). VMx runs the equality comparison, the validators, and, for deny, the
snapshotter on the candidate before changing anything. If one of them throws
(or panics in Rust), the exception reaches the caller and the form is exactly
as it was. The model, snapshot, errors, dirty and valid state, and command
state are unchanged, and no notification is sent. A failure never becomes a
validation error.
Validators receive the candidate as their argument; reading the form's model from inside a validator returns the previous model.
The form holds no lock while an equality comparison, a validator, the
snapshotter, or resetOnApproved runs (spec chapter 20 §5.4, ADR-0215). Thus
other threads do not wait for these callbacks:
- A read from another thread returns the committed state at once.
- Commits stay serialized. When another thread commits first, the overtaken update runs again against the new state.
- A
Dispose()from another thread returns at once. The preparing update commits nothing, and the teardown runs when that update returns.
If a validator itself disposes the form or makes another edit, the interrupted update commits nothing and the newest edit stands.
SetModel / set_model that begins after disposal is also a complete no-op.
It returns before null or equality work, leaves the live model and snapshot
unchanged, does not re-run validators, and cannot change errors, dirty/valid
state, approve command state, or notification channels. A set admitted before
disposal keeps the normal mutation contract. Upstream async work should still
be cancelled for resource control; this guard only rejects a late form result.
Strict mode gates approve-command eligibility on IsValid && IsDirty.
The direct awaitable approve path in all five flavors gates on validity,
disposal, and the one-approval-at-a-time rule below, so a strict, valid, clean
form may still be persisted explicitly.
6.2.8.2.3.1. Settled Model Publication¶
An accepted unequal SetModel / set_model call is one synchronous edit
transaction. VMx installs the candidate, recomputes validation, errors, dirty
state, and approve-command state, then publishes exactly one model
PropertyChangedMessage on the configured hub. Publication is last, so a
synchronous hub observer sees the complete settled form state. The property
name follows the flavor idiom: "Model" in C# and "model" in Python,
TypeScript, Swift, and Rust.
The equality check uses the same configured or idiomatic equality as dirty
tracking. An equal candidate is a complete no-op: VMx retains the current model
and does not validate, invalidate commands, or publish. Only strict mode compares
dirty state during an update (ADR-0216). A strict SetModel runs three
equality comparisons and a strict deny two. A non-strict SetModel runs one,
and a non-strict deny runs none. A re-entrant hub or
CanExecuteChanged observer may assign another unequal value; each accepted
call settles and publishes once before returning.
A call made from a validator, an equality comparison, the deny snapshotter, or
an ErrorsChanged observer of SetModel or deny is nested (spec chapter 20
§5.4, ADR-0180). A nested SetModel or deny commits at once, but it returns
before its notifications. The outermost update sends them, error maps first,
before it returns.
An approval started from a validator calls its persister only after that, so do not block on it inside the callback. If the callback then disposes the form, the queued notifications are dropped and the persister is never called.
If a send of the queued notifications fails, the outermost update sends no later notification and its scopes still close (ADR-0216). Each queued approval whose persister has not started is released: its persister is never called, and its awaiter completes normally. The send failure then reaches the caller.
DenyCommand keeps its explicit ordered pair: one FormRevertedMessage, then
one idiomatic model property message after the revert settles. A successful
reset-after-approve publishes through OnApproved only and does not emit a
model property message.
6.2.8.2.3.2. Declarative Submit-Then-Clear¶
Configure reset-after-approve when a successful submission should leave the
form pristine with a derived next model. VMx captures the model before awaiting
persistence, persists it, checks disposal, invokes the reset once, snapshots
the reset result twice for independent live and snapshot values, revalidates,
and commits the transition. OnApproved then emits the captured persisted
model while observers see the already-reset form.
The reset wins over a SetModel racing the persistence wait. It does not run
for invalid approval, persistence failure or cancellation, disposal during
persistence, or deny/revert. If the reset or snapshot preparation fails,
persistence has already succeeded but local state is not changed and
OnApproved does not fire. Awaitable approval throws that failure; the command
path emits it once on ApproveErrors. A retry can therefore repeat external
persistence and should be handled as such.
6.2.8.2.3.3. One Approval At A Time¶
A form runs at most one approval at a time (spec chapter 20 §5.3, ADR-0143).
When an approval is admitted, VMx marks it in flight before capturing the model
and calling the persister, and the approve command's CanExecute turns false.
While it is in flight, another approve call through either the command or the
awaitable path does nothing: it does not call the persister, change state,
throw, or emit on OnApproved or ApproveErrors. A double-clicked Save button
therefore persists once.
Editing and deny are not blocked. A SetModel or deny during the save keeps its
normal behavior: the approval still commits the model it captured, and a
configured reset still wins.
When the approval settles, VMx clears the in-flight mark first, then publishes
any ErrorsChanged, one CanExecuteChanged, and the outcome on exactly one
channel. Code that reacts to the outcome, including an OnApproved subscriber
or the code awaiting ApproveAsync, sees an idle form and can approve again.
To save again after the current save, await it (or react to OnApproved) and
then approve; do not rely on a second call made during the save.
6.2.8.2.4. Cross-Language Surface¶
| Concept | C# | Python | TypeScript | Swift | Rust |
|---|---|---|---|---|---|
| Type | FormVM<TM> |
FormVM[TM] |
FormVM<TM> |
FormVM<Model> |
FormVm<M> |
| Builder | FormVMBuilder<TM> |
FormVMBuilder[TM] |
FormVM.builder<TM>() |
FormVM<Model>.builder() |
FormVm::builder() |
| Mutator | SetModel(...) |
set_model(...) |
setModel(...) |
setModel(...) |
set_model(...) |
| Awaitable/direct approve | ApproveAsync() |
approve_async() |
approveAsync() |
approveAsync() |
approve() |
| Reset builder | ResetOnApproved |
reset_on_approved |
resetOnApproved |
resetOnApproved |
reset_on_approved |
| Approval subscription | OnApproved.Subscribe(...) |
on_approved.subscribe(...) |
onApproved.subscribe(...) |
onApproved.sink { ... } |
subscribe_approved(...) |
Each approval subscription detaches on its own: dispose the C# IDisposable,
Python disposable, or TypeScript Subscription, cancel the Swift
AnyCancellable, or dispose or drop the Rust ApprovalSubscription. Form
disposal releases every remaining subscriber, and a registration made after
disposal keeps nothing.
Every flavor signals form disposal to an approval subscriber. C#, Python,
TypeScript and Swift complete OnApproved. Rust calls the completion callback
of subscribe_approved_with_completion(...) once (ADR-0210). That callback
runs at once for a subscription made after disposal, and never for a handle
detached before disposal. Rust subscribe_approved takes no completion
callback. Rust's deprecated on_approved registration lasts until the form is
disposed (ADR-0139).
Builder examples use the idiomatic name but the same captured-model contract:
var form = FormVM<OrderDraft>.Builder()
.Initial(initial)
.Persister(SaveAsync)
.ResetOnApproved(saved => OrderDraft.Empty(saved.CustomerId))
.Build();
form = (FormVM.builder()
.initial(initial)
.persister(save)
.reset_on_approved(lambda saved: OrderDraft.empty(saved.customer_id))
.build())
const form = FormVM.builder<OrderDraft>()
.initial(initial)
.persister(save)
.resetOnApproved((saved) => OrderDraft.empty(saved.customerId))
.build();
let form = try FormVM<OrderDraft>.builder()
.initial(initial)
.persister(save)
.resetOnApproved { saved in .empty(customerID: saved.customerID) }
.build()
let form = FormVm::builder()
.initial(initial)
.persister(save)
.reset_on_approved(|saved| Ok(OrderDraft::empty(saved.customer_id)))
.build()?;
6.2.8.2.5. Example¶
The Notes Workspace editor is the best concrete reference:
- C#: NoteFormVM.cs (
examples/csharp/avalonia/NotesShowcase/ViewModels/NoteFormVM.cs) - Python: note_form_vm.py (
examples/python/textual/notes_showcase/src/notes_showcase/viewmodels/note_form_vm.py) - TypeScript: noteFormVM.ts (
examples/typescript/react/notes-showcase/src/viewmodels/noteFormVM.ts) - Swift: NoteFormVM.swift (
examples/swift/notes-showcase/Sources/NotesShowcaseCore/ViewModels/NoteFormVM.swift)
All four compose a strict inner FormVM rather than subclassing it, then layer
editor-specific commands and notifications around that core workflow. The Rust
TUI companion's NoteFormVm also wraps a strict FormVm
(viewmodels.rs (examples/rust/tui/notes-showcase/src/viewmodels.rs)).
The examples below are simplified illustrations of the FormVM construction in
those files. They are not copies, and the source files hold the current code.
_form = new FormVM<NoteModel>(
initial: note,
persister: PersistAsync,
hub: Hub,
strict: true,
validators: new Dictionary<string, Func<NoteModel, string?>>
{
[nameof(Title)] = note => string.IsNullOrWhiteSpace(note.Title) ? TitleRequired : null
});
form = FormVM(
initial=note,
persister=self._persist,
hub=self._hub,
strict=True,
validators={"title": lambda m: _TITLE_REQUIRED if not m.title.strip() else None},
)
this.#form = new FormVM<NoteModel>({
initial: note,
persister: (m) => this.#persistAsync(m),
hub: this._hub,
strict: true,
validators: {
title: (m) => m.title.trim().length === 0 ? TITLE_REQUIRED : null,
},
});
let form = FormVM<NoteModel>(
initial: note,
persister: { [weak self] n in
guard let self else { return }
try await self._repo.saveNote(n)
},
hub: hub,
strict: true,
validators: [
"title": { model in
model.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? Self.titleRequired
: nil
}
]
)
6.2.8.2.6. TypeScript Snapshot And Equality Defaults¶
TypeScript uses structuredClone for the default snapshot. Functions,
WeakMap/WeakSet, host handles, and objects containing those values are not
structured-cloneable. If the default fails during construction, approve
snapshot advance, or deny/revert, FormVM reports that phase and the first
failing enumerable top-level field it can safely identify. The native error is
preserved as cause; the diagnostic never renders field values.
The matching default structural equality understands the same common binary
values: buffers compare by concrete buffer type, length, and bytes; DataView
and typed-array views compare by concrete view type and their visible byte span.
Separately allocated equal bytes therefore remain clean, while changed bytes or
a different binary interpretation make the form dirty. Inject equals when a
domain needs reference identity or a different binary policy.
A model and its default snapshot compare clean for every value the default
comparator supports: primitives (NaN equals NaN, -0 equals 0), BigInt,
Date by instant (an invalid Date equals another invalid Date), RegExp
by source and flags, the binary values above, Blob, File, and CryptoKey
(see below), arrays, plain objects by own enumerable keys including
undefined-valued keys, and cycles. Map keys and
Set members keep SameValueZero membership, so object keys, which
structuredClone copies, make a fresh form dirty; inject equals to compare
them structurally.
Error values compare by what structuredClone keeps (ADR-0135). Two errors
are equal when they have the same kind, the same own message, and equal own
cause values. The comparison of cause is recursive, and a cycle through
cause terminates.
The kind is the standard error named by name: Error, EvalError,
RangeError, ReferenceError, SyntaxError, TypeError, or URIError. Any
other name, such as a custom subclass or AggregateError, clones and compares
as a plain Error.
The clone does not keep the stack, custom properties such as a code, an
AggregateError's errors, or subclass identity, so VMx does not compare
them. Thus a model that holds a custom error starts clean, and a change to only
its code does not make the form dirty. Inject a matching snapshotter and
equals when a domain needs those details.
Node 20's structuredClone throws for an error whose cause chain leads back
to itself. On Node 20, a model that holds such an error needs an injected
snapshotter; Node 22 and later clone it.
A DOMException compares by its name and message (ADR-0152), which its
clone keeps on Node 22 and later. It never equals another error, and its
cause and custom properties are not compared. Node 20's structuredClone
returns a plain object for a DOMException, so on Node 20 a model holding one
needs an injected snapshotter and equals.
A Blob, File, or CryptoKey compares by the state its clone keeps
(ADR-0253). A Blob compares by size and type. A File also compares by
name and lastModified when it is compared with another File; against a
Blob it compares by size and type only. A CryptoKey compares by type,
extractable, algorithm, and usages. Their bytes and key material are not
compared, so two values with the same state are equal even when their contents
differ. Inject equals for a domain that needs the contents. Node 20.5 and 22
clone a File as a Blob, which keeps no name or lastModified. On those
runtimes a replacement that differs only in name or lastModified is committed
but does not make the form dirty. Node 24 and 26 keep the File. On every
runtime, a File and a Blob of the same size and type are equal in either
direction, so a replacement of a Blob by a same-size, same-type File is
dropped, and so is the reverse replacement. The CryptoKey clean-start check
runs where the runtime's clone keeps a CryptoKey.
Field localization inspects data-property descriptors, performs no writes, and
does not invoke getters a second time. User-defined accessors or proxy traps can
have side effects during the original structuredClone call or descriptor
inspection, so FormVM deliberately omits the field name when localization
cannot be guaranteed.
When a model carries an opaque, non-cloneable payload beside ordinary form data, keep the payload by reference. Define explicitly which plain fields participate in dirty tracking, and configure both hooks together:
const snapshotDraft = (model: DraftModel): DraftModel => ({
...structuredClone({ title: model.title, body: model.body }),
payload: model.payload,
});
const equalsDraft = (a: DraftModel, b: DraftModel): boolean =>
a.title === b.title && a.body === b.body;
const form = FormVM.builder<DraftModel>()
.initial(initial)
.persister(persistDraft)
.snapshotter(snapshotDraft)
.equals(equalsDraft)
.resetOnApproved((approved) => ({
...approved,
payload: undefined,
}))
.build();
Here payload is excluded from dirty tracking, restored by reference on deny,
and cleared only after its captured value is persisted. If reference identity
should count as dirty, include a.payload === b.payload in equalsDraft.
VMx does not provide snapshotExclude: exclusion without an explicit equality
policy would make dirty and revert semantics ambiguous.
6.2.8.2.7. C# Snapshot And Equality Defaults¶
C# compares the model and the snapshot with object.Equals. The default
snapshotter is a System.Text.Json serialize and deserialize round-trip, so
the snapshot holds a new instance of each collection field. A record's
synthesized equality compares a collection field, such as an
IReadOnlyList<string>, by reference. A new form for such a record is
therefore dirty before any edit. A strict form enables ApproveCommand at
once, and a SetModel call with an equal-content list publishes a Model
message.
C# FormVM takes no equality parameter, so the model's own equality is the
hook. Override Equals and GetHashCode to compare the collection element by
element:
public sealed record Note(string Title, IReadOnlyList<string> Tags)
{
// Compare Tags element by element, not by reference.
public bool Equals(Note? other) =>
other is not null
&& Title == other.Title
&& Tags.SequenceEqual(other.Tags);
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Title);
foreach (var tag in Tags)
hash.Add(tag);
return hash.ToHashCode();
}
}
With this override, a new strict form is clean, ApproveCommand cannot
execute, and an equal-content SetModel publishes no Model message. A
changed element still makes the form dirty.
6.2.8.2.8. Common Pitfalls¶
- Treating
FormVMas a drop-inComponentVMsubclass. It is a distinct workflow primitive. - Relying on shallow copy semantics for nested mutable models. Inject a custom
snapshotter and matching equality predicate where the default is not
appropriate. C# takes no equality predicate; override the model's
EqualsandGetHashCodeinstead. - Using a C# record with a collection field and the synthesized equality. The
form is dirty before any edit; compare the collection element by element in
the model's
Equals. - Ignoring
ApproveErrorson fire-and-forget command paths. - Expecting a second approve made during an in-flight save to save again. It is refused; await the first approval, then approve again.
- Reading
Modelfrom inside a validator to see the candidate. Validators get the candidate as their argument; the form still shows the previous model until the update commits. - Retrying blindly after reset failure; the external persist already succeeded.
- Re-implementing save/cancel/dirty plumbing in every editor instead of composing the primitive once.
- Keeping a form-specific “zombie assignment” flag solely to stop late
setModelcalls. VMx rejects those calls after disposal; retain only cancellation that still owns application resources.