Internal contract (for contributors)
How the engine, the node tree and the codec work inside Klyroo.Form.Core. For contributors and for code that builds on the internals, not needed to use the library.
On this page
This note is for the people who build on the internals of Klyroo.: the typed components (KlyFormEngine, KlyFormPage, KlyFieldTemplate, FormService) and the agent bridge. Nothing here is public API. Klyroo., Klyroo. and Klyroo. see these types through Internals; other packages go through IFormRuntime.
Layers
FormSchema.For<TModel> --builds--> FormSchema<TModel> --holds--> FormDefinition (FieldNode, StepNode, SectionNode, TabNode)
+ IFieldBinding<TModel> list, typed handles, hooks
DynamicFormSchema --compiles-> CompiledDynamic --holds--> FormDefinition + a map from each public schema object to its node
FormController<TModel> --wraps--> FormEngine (one per controller) <--wraps-- DynamicFormControllerA schema (either kind) owns a FormDefinition, which is immutable and shared. A controller owns one FormEngine, which runs that definition. Every delegate in a definition takes the FormEngine; the public wrappers adapt user delegates with engine., the public controller that created the engine, so a user condition receives FormController or Dynamic, never the engine.
Create an engine in two steps, because a default factory or a skip condition may call back into the owner: new FormEngine, assign it to the owner field, then engine..
FormDefinition and nodes
FormDefinition is the old FormSchema data: FormKey, Title, Description, Eyebrow, Columns, ShowStepper, ValidateMode, Messages, IgnoreDirtyPaths, Fields, Steps, Sections, and the hooks OnBeforeSubmit, OnSubmit, OnBeforeNext, OnBeforePrevious (all Func). AllNodes() walks every node that is not a column of a list.
FieldNode is the old FormFieldSchema, with the same members: Key, Kind, texts, DefaultValue, DefaultFactory, Required, RequiredWhen, Trigger, DependsOn, Disabled, DisabledWhen, Condition, Ignore, OmitFromOutput, Span, Min, Max, Step, Accept, MaxFileSize, CustomKey, MaxLength, Multiple, Clearable, Options, OptionsFactory, OnCreateOption, Password, Validators (ValidatorRule), AsyncValidators (Async), TransformInput, TransformOutput, Watch, OnClick, the display members, Fields (children, or the columns of a list) and Tabs. Two additions:
Source: the public schema object the node was compiled from (Dynamic,Field Schema Dynamic, ...), orStep Schema nullfor a typed node.Dynamicuses it to give public schema objects back.Form Controller ControlCheck: for a typed field, says why a control value is not a value of the field type (nullwhen it is). The engine does not apply it inSetValue, which accepts any control value so a control can hold text such asabc, butCheckValueSyncapplies it when the field is validated, after the rules of the field and whatever the validation mode: a control value that is there and is not a value of the type is the errorFormMessages., for a field and for a cell of a list. So a draft withInvalidValue {"Day":"abc"}for aDateOnly,["x","y"]for aFormDateRange, or free text from a custom control, restores without error, failsValidateand the submit, and never reaches the write, which would throw. The rules keep their own wording for numbers and identifiers (WholeNumber,NumberOutOfRange,Invalid).Identifier FieldNode.reads JSON through the codec, which includes the same check.JsonReader
Values stored in the engine are control values: a string for text-like kinds (dates and times as yyyy-MM-dd, yyyy-MM-ddTHH:mm, HH:mm), double or decimal for Number and Slider, int for Rating, bool, the option text for single choices, List for tags, checkbox groups, multiple choices and a date range (two items), FormFileValue or List for files, whatever a custom renderer stores for Custom, and List for the rows of a list.
FormEngine
The members the components and controllers use (all internal, same behavior and tests as the old FormController):
| Area | Members |
|---|---|
| Lifecycle | FormEngine, Start, Reset, Reset, Dispose(), Changed, Owner, Schema (the definition) |
| State | GetValue, GetValue, TryGetValue, GetInitialValue, SetValue, MarkTouched, ResetField, ResetSection, InternalState, DirtyPaths, IsDirty, BuildOutput() |
| Errors | Errors, GetError, SetError, ClearError, SetFormError, FormErrors, GetErrorEntries, HasBlocking, SubmitFailed, Submit, FormErrorKey, Messages, UseLocale |
| Fields | AllFields, ActiveFields, Current, Should, IsFieldRequired, IsFieldDisabled, GetFieldOptions, Create, IsSectionVisible |
| Rows | GetArrayItems, AddArrayItem, RemoveArrayItem, SetArray, Mark, GetArray, CellPath |
| Validation | Validate, ValidateAsync, IsValidating, HasPending, Cancel |
| Steps and submit | IsStepped, CurrentStep, CurrentStepIndex, IsFirstStep, IsLastStep, NextStepAsync(), Previous, SubmitAsync(), SubmitAsync with handler, IsSubmitting, GetSection |
| Drafts | ExportState, RestoreDraft (a FormDraft keeps its values internal) |
| Statics | IsStateless, IsContainer, IsEmptyValue |
FormEngine is not thread safe and raises Changed synchronously, like the controllers.
Typed side
FormSchema exposes to the internals: Definition, Bindings (one IFieldBinding per bound field), Writable, Factory, State (checks and hooks), TryFindNode, ToInput, PlanWrite and Create.
A handle (FormField, FormListField, FormItem) carries Key, Node, and for a field Codec and Binding. They are assigned when the schema is built, so a handle used while the schema is still being declared throws.
FormCodec (abstract, one per field, chosen from the final kind of the field):
| Member | Meaning |
|---|---|
Kind |
the kind the codec was made for |
ToControl |
the control value of a value |
TryFromControl |
ControlValue., Empty (the default is given) or Invalid (the default is given, and a write refuses it) |
From |
the value, or the default |
Format and TryParse |
invariant text (lists are comma separated), for hidden inputs and a future static post |
TryRead and TryReadJson |
the JSON of an agent, read with the kind rules (Form: bounds, options by value or label, date formats), then with the exact digits of a number, then checked against the type. The bounds Min and Max are compared with the exact number (Form), in FormJsonCoercion and in the engine's number rule at validation alike. TrySet stores the control value TryRead gives |
WriteJson |
the value as JSON, the way a control value is written; nothing calls it yet, because drafts and WriteValue write the control value the engine holds (which can be text that is not a value) |
Nullable |
whether an empty text is null for a string member |
ScalarCodec covers a single value, a list of strings and files with FormValueMap, which compares types and never inspects them. MultiCodec is a multiple choice (the control holds the formatted option values). ListCodec maps List to items through the ListRows columns; it makes new items, so it serves reads (Get, TryGet), never writes.
IFieldBinding reads a member into a control value (ReadControl) and plans a write (Plan) into a FormWritePlan, which converts everything before it sets anything and rolls back on demand. Implementations: TypedBinding (typed delegates from CreateDelegate, composed through HolderPath and NestedHolder for Group), ReflectedBinding (a member known only at run time: AllMembers), the column bindings of a list, which are IFieldBinding, and the two collection bindings, RowsBinding (a List) and MultiBinding (a MultiSelect), which share Collection.
Collection binds a collection member through the property of its holder. A chain written without Group is refused when the schema is built (List and MultiSelect give an Argument that points to Group), and so is a member with no setter whose type cannot be changed in place (an array, IReadOnlyList, IEnumerable). A write plans one step: when the collection the member holds is an ICollection that is not read-only and not an array, it is made to hold the new items in place (positions kept, and put back by the same routine on a rollback); otherwise the setter gets a new List or array. A collection that already holds the new items, in order, is not written at all. A getter-only member whose value turns out to be null or read-only throws at planning time, before any change.
RowsBinding writes a row into the item it was loaded from. The engine keeps rows as dictionaries, and a RowOrigin (a Conditional from the row dictionary to the item) remembers the item beside the row, so the item is never a value of the row: it is not in a draft, in the dirty check or in the JSON. ListRows. sets it, and CloneValue carries it over to the copies the engine makes (snapshot, BuildOutput). RowsBinding. writes the columns into the origin only when the collection holds that item now, so a row loaded from another model, a draft restored row and an added row all get a new item, and a write into a new model never changes the rows of the model the form was loaded from. Each planned list is recorded in FormWritePlan., and FormController. with a target sets the origin of the engine rows to those items after a successful save, before the engine retakes its snapshot.
IFormRuntime
FormController and Dynamic implement IFormRuntime. Fields returns the FieldAccess views (Engine/): the stateful leaf fields of the form, whether in effect or not, without stateless blocks and hidden inputs. FieldAccess reads IsHidden from ActiveFields, IsOffPage from the current step, and writes JSON through FieldNode. for a typed field (the codec's TryRead: the rules of the agent Form, with their tests in Form, plus the exact digits of a number and the check against the type) and through Form for a dynamic field, then engine.. A dynamic Number field keeps a double, as before; a typed one stores a decimal when the digits would not fit a double, so long., 9007199254740993 and a decimal of 28 digits arrive exactly. Drafts do not go through the codec: a draft holds control values, which can be text that is not a value yet (abc in a number field) and must survive a reload; FormDraft. and Form read its numbers with the same NumberFromInput and NumberToControl rules, and the typed check happens when the field is validated. A sensitive field (Password, OneTimeCode) writes null from WriteValue.
How the components use this
The Blazor components of Klyroo. are built on the engine and the node tree:
- One renderer.
FieldNodeView(namespaceKlyroo.) draws aForm. Internal FieldNodeof aFormEnginefor typed and dynamic forms. Razor makes every component public and public parameters cannot have internal types, so the hidden components (FieldNodeView,FormShell,FormPageShell, all[EditorBrowsable) read their internal parameters ((Never)] Engine,Node,Templates,Submit, ...) inSetParametersby name and are not meant to be used directly.Async KlyDynamic,Field View KlyFormFieldView,<TModel> KlyFormEngine,<TModel> KlyFormPage,<TModel> KlyDynamicandForm Engine KlyDynamicare thin: they pick a controller and hand itsForm Page Engineto the shared component.FormShellandFormPageShellown the subscription toChanged, the focus after a failed submit,FormRunand the markup of the header, stepper, sections and actions. - Engine access.
IEngineOwner(internal) is implemented byFormControllerand<TModel> Dynamic.Form Controller FormRuntime.reaches the engine, soEngineOf (IFormRuntime) KlyFormandError Summary KlyFormtake anNavigation Guard IFormRuntime.FormUiStateis keyed by the engine, and so are the element ids:FormEngine.(IdPrefix kly-ff-, one number per engine) starts every id the renderer, the error summary and the focus helper build, so forms with the same keys do not collide.<n>- - Control bindings. The renderer builds a
ControlBinding(value,Current(),Set,Commit,Blur, error, flags, ids, slot, cell or not) for every control.DynamicandControl Context Formwrap it. The typed context is made byControl Context <TValue> FieldNode.over theContextFactory FormCodecof the field (<TValue> Valueiscodec.,From Control Or Default (binding. Value) SetandCommitstorecodec.,ToControl (value) TextandSetTextare the string boundary:NumberFromInputfor numbers,TryParsefor the other kinds, and text that is not a value stays as it is).FieldNode.is what a renderer must match.ValueType - Custom renderers. A control is drawn by, in order: the
KlyFieldTemplateregistered for the key of the field in theFieldof the engine (not for a cell of a list), then for aTemplate Registry Customfield theFieldTemplatesof a dynamic component, then the renderer registered inKlyroofor its key and value type (the registry is keyed byForm Options (key, type),nullfor a dynamic renderer, so they coexist). A typed renderer matches only a field whoseValueTypeis the one it was registered for, a dynamic one only a dynamic field; anything else shows the "no renderer" notice. - Typed hosts.
TypedFormHostdoes what<TModel> KlyFormEngineand<TModel> KlyFormPageshare: it picks the controller (<TModel> Form, else one made fromSchemaandModel, reloaded withResetwhen another model instance arrives), and runs(model) FormControllerwith<TModel>. SubmitAsync (save, model, ct) OnSaveas the save step, capturing the model forOnSubmit. The engine components cascade the controller asFormControllerso<TModel> KlyFormFieldViewandKlyFieldTemplatefind it. - Overlays.
FormServiceholds aFormOverlay(controller, task completion source, a render fragment that opens<TModel> KlyFormEngine);<TModel> KlyFormProviderrenders one overlay for it and one forDynamic, so a typed and a runtime form can be open together.Form Service
Agent bridge: RegisterForm replaces RegisterForm. Everything it read from FormController and FormFieldSchema is on IFormFieldAccess (Key, Kind, Label, Sensitive, IsHidden, IsOffPage, IsDisabled, Options, WriteValue, TrySet, Clear, Toggle, Reset) and IFormRuntime (FormKey, Title, IsDirty, IsStepped, CurrentStepKey, SubmitAsync, Reset, NextStepAsync, Previous, Changed). AgentArgs and Form can be deleted once the bridge passes JsonElement to TrySet: the rules, the exact-number handling (RawNumber) and the option matching by normalized label are in Engine/ and Engine/.