CRUD / foldkit-crud
An editor
An editor joins a form, the mutation its value feeds, and the Entity they
share. EditPostForm is a Form.make result and EditPostMutation a Remote
mutation over the same input struct, as in
examples/entity; Blog is that application's Entity
domain.
import { Crud } from 'foldkit-crud'
import { Bundle } from 'foldkit-bundle'
import { Remote, type RemoteClient } from 'foldkit-remote'
import { Surface } from 'foldkit-surface'
const Editor = Crud.editor('PostEditor', { form: EditPostForm, mutation: EditPostMutation })
// The editor is a Submodel of the page: a Model field and a Message variant.
const Base = Bundle.compose({ remote: Remote.Model }).pipe(
Bundle.withMessages(Remote.messages),
Bundle.withChild('editor', Editor.bundle),
)
const App = Surface.application(Base)
const Data = Remote.make({
model: App.model.remote,
entities: Object.values(Blog),
mutations: [EditPostMutation],
})
// Where it lives: its slice of the Model, and the domain it saves through.
const PostEditor = Editor.at({ data: Data, model: App.model.editor })
// Its placement needs the domain, so it is given once the domain exists.
const Page = Base.pipe(
Bundle.withServices<RemoteClient>(),
Bundle.configure('editor', PostEditor.placement),
)
const Placed = Page.children.editor
const { placements } = Page
const update = PostEditor.after(
placements.update((model, message) =>
Remote.reduces(message) ? { model: Data.reduce(model, message) } : { model },
),
)
const subscriptions = Data.subscriptions({ editor: PostEditor.active })Crud.editorchecks at compile time that the form's submitted value matches the mutation's input.- Over a variant Entity's form (an input with
_tag; seefoldkit-form), the editor loads each row as its case and fills that case's keys alone. Editor.bundlewraps the form's Bundle and keeps its Messages (Changed,Submitted, and the rest) intact for views.Bundle.composedeclares the page first, thenBundle.configure('editor', PostEditor.placement)supplies the domain-dependent placement (see composing a parent).Editor.atbinds the editor slice (App.model.editor) and Remote domain, returningplacement(onOut+viewInputs),busy(model),active,after(update)(andsync),status(model),saveError(model),refresh(model), andtarget(model).- Saves execute Commands needing
RemoteClient, so the page declaresBundle.withServices<RemoteClient>().
What starts the work
| Call | What happens |
|---|---|
Crud.editor(...) / Editor.at(...) | Builds the editor configuration without sending requests |
Placed.helpers.open(id) | Returns an Update Step to open a record for editing |
Data.subscriptions({ editor: PostEditor.active }) | Installs the loader subscription with RemoteClient |
PostEditor.after(update) | Fills the form once loaded and reconciles status |
A valid submit, through placement.onOut | Returns the mutation Command; Remote settles the save |
Include the placement's own Subscriptions when your form uses async checks or
stateful controls. Only the mutation's outcome moves status to Saved.
Opening it
open, blank, and close are Update Steps returned from the placement's
helpers:
Placed.helpers.open('p2') // edit p2: the form empties, then fills when the value arrives
Placed.helpers.blank() // a new one: nothing to load, editing at once
Placed.helpers.close()When create and edit share one form whose id is an Option, a blank() form
submits Option.none() (Create) and an open(id) form submits Option.some(id)
(Update). After a create saves, the form resets to blank (preserving any edits
typed while the request was in flight). Declared writes (Write.update and
Write.insert) use two separate editors.
Its status
| Status | When |
|---|---|
Closed | Nothing is open |
Loading | An ID is open and its current values are in flight |
Editing | The form is active with no pending or settled save |
Saving | This editor's mutation is pending |
Saved | The mutation applied |
SaveFailed | The save failed; drafts stay intact and saveError(model) has details |
Conflict | Server refused with Refusal.conflict (row changed elsewhere) |
Moved | A revision-pinned declared write saw the row move after loading |
LoadFailed | Initial load failed; call refresh(model) to retry |
NotFound | The record is absent or deleted; outranks earlier saves |
Any edit after a save moves status back to Editing.
Field-level server refusals (Refusal.field(key, reason)) attach directly to
the matching key (Message.Refused) while it still holds the refused value, and
status becomes SaveFailed. Invariant refusals (Refusal.invalid) highlight
the keys named in their path.
The editor also loads fields referenced by Entity invariants (Entity.judgedBy)
and calls form.over automatically, catching cross-field invariant errors
client-side before sending. Read-guarded fields withheld by the server remain
undecided on the client and are judged by the server on save; redacted fields
judge against their redacted value unless omitted.
A save in flight
While a save runs, busy(model) is true and viewInputs set submitting
(aria-busy, data-submitting, and aria-disabled on the submit button).
busy reads directly from Remote's ledger by request ID and clears as soon as
the mutation settles.
- Submitting while busy returns the Model unchanged without starting a second write.
- Key refusals render on the matching field; general refusals (conflicts
or unpathed invariants) render in the form's
failureSlot. - Network failures render in
failurewith a retry trigger sendingData.retrywith the original operation ID; editing the form starts a fresh write. - A landed create resets the form to blank with an
aria-disabledsubmit button that keeps focus and announces missing fields if pressed.
foldkit-mixins-crud's EditorView leaves SaveFailed and Conflict to the
form's failure Slot so failures announce once, keeping transport messages in
saveError(model) for diagnostics. Customize default sentences with words:
const Worded = Crud.editor('PostEditor', {
form: EditPostForm,
mutation: EditPostMutation,
words: {
failed: 'Could not save. Check your connection and try again.',
conflict: 'Someone else saved this first, so your changes were not saved.',
refused: 'This could not be saved.',
},
})Passing a custom failure in the form's view inputs overrides these strings.
How it treats the form
- Fills once per open: refetches or live updates leave user drafts alone;
calling
openagain clears and refills. - Selects form keys +
Entity.judgedBy: unmapped keys (Entity.unmapped) start empty and skip loading. - Validates before sending: invalid submits run form validation and checks without starting a mutation.
- Declared writes send deltas: with
Mutation.write, saves include only keys changed from what the form loaded or last saved, avoiding overwrites on untouched fields; new blank forms send all keys. - Revision-pinned writes track saves: after a revision-expected write lands,
the form adopts the new revision so follow-up saves succeed cleanly while
external edits transition status to
Moved. - Status follows edits: editing after a save resets status to
Editing(orMoved), while late responses still attach field refusals if they land.
Drawing it
Lift any Submodel form view into the editor with Crud.editorView:
import { FormView } from 'foldkit-mixins-form'
const DrawnEditor = Editor.bundle.pipe(
Bundle.withView(Crud.editorView(FormView.submodel(EditPostForm, FormView.define(EditPostForm)))),
)
// Place it as before: Bundle.withChild('editor', DrawnEditor)Where the page draws the placement of DrawnEditor:
Placed.view(model, h, { options: pickers(model), words: { submit: 'Save' } })Pass locks: May.locks(Blog.Post) (foldkit-guard) to Crud.editor and forward
locked: PostEditor.locked(model) to the form view so read-only keys render
locked while loaded (new blank forms unlock all fields; the Source must select
may, and the server still enforces writes).