Form / Limits and guards from a metakit declaration
Refuse an action its guard refuses
A metakit Transition is a state change with a when guard: a withdrawal
goes through when the account is open and the amount is within the balance.
can(model, transition, state) judges that guard with the form's values as the
transition's input and state as what you know of the account:
import { Eq, Transition, Verdict } from '@doeixd/metakit'
const Account = Schema.Struct({ balance: Usd, frozen: Schema.Boolean })
const Withdraw = Transition.make({
state: Account,
input: WithdrawInput,
when: ({ state, input }) =>
Expr.all(Eq.is(state.frozen, false), Money.lte(input.amount, state.balance)),
apply: ({ state, input }) => [Transition.set(state.balance, Money.sub(state.balance, input.amount))],
})
const { can } = Declared.of(WithdrawForm)
const verdict = can(WithdrawForm.initial, Withdraw, { balance: Money.minor(Usd, 10_000), frozen: false })
Verdict.isFalse(verdict) // false: no amount is typed yet, so the verdict is Unknown, not FalseThe answer has three values, not two:
True: every value the guard reads is known, and it holds.False: it fails, whatever the unknown values turn out to be. A frozen account isFalsebefore an amount is typed. So is a guard that cannot be worked out over the values it has: metakit refuses a whole-number result past ±(2^53−1), where JavaScript numbers stop being exact, and the transition refuses the same values.Unknown: the guard reads a value that is not typed yet, does not decode yet, or comes from an opaque function. A draft that does not read as an amount isUnknown, notFalse.
Refuse the control only on False, and leave it pressable on Unknown. h is the form's HTML builder, as in the h.input example above:
h.button([...(Verdict.isFalse(verdict) ? [h.AriaDisabled(true)] : [])], ['Withdraw'])Unknown is not a promise that the withdrawal will go through. Run the
transition in your update when the form submits (Transition.run refuses it
there if the guard fails), and use aria-disabled rather than disabled, as
the form's own submit button does, so Enter still reaches your update.