qat

Forms

form(schema) puts forms on the browser's own constraint validation — the same rules the browser enforces and :invalid styles, with reactive values, errors and submit state. It is @qatjs/form, which qatjs init lists in package.json (in an app made another way, npm i @qatjs/form):

.qx21 linesOpen in the playground
// signup.qx
import { form } from '@qatjs/form'

export default function Signup() {
  let f = form({
    email: { type: 'email', required: true, message: { valueMissing: 'Enter your email', typeMismatch: 'That is not an email' } },
    password: { type: 'password', minLength: 8 },
    again: { type: 'password', validate: (v, all) => v === all.password || 'The passwords differ' },
  })
  const save = async (values) => console.log('saving', values)
  return (
    <form novalidate on:submit={f.submit(save)}>
      <input ref={f.field('email')} />
      {if (f.errors.email)}<p class="error">{f.errors.email}</p>{/if}
      <input ref={f.field('password')} />
      <input ref={f.field('again')} />
      {if (f.errors.again)}<p class="error">{f.errors.again}</p>{/if}
      <button disabled={f.submitting}>Sign up</button>
    </form>
  )
}
  • f.field(name) is a ref: it sets the schema's attributes on the element (type, name, required, min/max/step, minlength/maxlength, pattern), and keeps the element and f.values[name] in sync both ways (numbers for type: 'number', booleans for checkboxes). Radios take the same f.field(name) each, and the field is the checked one's value; a <select multiple> is the list of what is selected (in the browser: a post without JavaScript gives its first). A select shows the field's value also when its options come after it.
  • Errors are the element's native validity, as a message: the schema's message (one string, or one per validity flag: valueMissing, typeMismatch, patternMismatch, tooShort, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, badInput), else the browser's own localized message. A field's error shows once it was blurred or a submit was attempted. The element's aria-invalid follows its validity from the start, though: a just-mounted empty required field already says aria-invalid="true", before any error is shown.
  • Messages in the user's language (@qatjs/core/i18n): write the message as a getter, which each check reads again, so the next check speaks the language chosen meanwhile: message: { get valueMissing() { return t('todos.required') } }. A plain valueMissing: t('todos.required') is read once, when the form is made. An error already shown changes at its field's next check (an input, a blur, a submit).
  • validate(value, values) adds a rule (it may compare fields) through setCustomValidity: return a message or false when invalid. false shows the schema's message, else the word invalid: return a message instead.
  • f.submit(handler) is an on:submit handler: it prevents the default, shows every error, focuses the first invalid field, or runs handler(values) (plain values) with f.submitting true meanwhile. A submit while one is pending (Enter in a field, with the button disabled) is ignored: one request at a time. Add novalidate to the <form> so the browser's bubbles don't block it.
  • f.valid, f.touched[name], f.setError(name, message) (server errors, cleared when the field is edited), f.reset().

Progressive forms: they work without JavaScript

On a server-rendered route (page(p, { mode: 'server' }), also 'static' and 'island'; see server rendering), the same form(schema) also works with JavaScript disabled, failed or still loading. You write nothing extra: no endpoint, no second schema, no server handler:

.qx27 linesOpen in the playground
// apply.qx (routes.js: '/apply': page('./pages/apply.qx', { mode: 'server' }))
import { form } from '@qatjs/form'
import { navigate } from '@qatjs/router'
import { applications } from '../applications.js'

export default function Apply() {
  let f = form({
    name: { required: true, minLength: 2, message: { valueMissing: 'Enter your full name' } },
    age: { type: 'number', min: 18, required: true, message: { rangeUnderflow: 'You must be 18 or over' } },
    consent: { type: 'checkbox', required: true, message: 'Confirm that the details are correct' },
  })
  const save = async (values) => {
    const id = await applications.add(values)
    navigate(`/apply/done?id=${id}`)
  }
  return (
    <form novalidate on:submit={f.submit(save)}>
      <label>Full name <input ref={f.field('name')} /></label>
      {if (f.errors.name)}<p class="error">{f.errors.name}</p>{/if}
      <label>Age <input ref={f.field('age')} /></label>
      {if (f.errors.age)}<p class="error">{f.errors.age}</p>{/if}
      <label><input ref={f.field('consent')} /> The details are correct</label>
      {if (f.errors.consent)}<p class="error">{f.errors.consent}</p>{/if}
      <button>Apply</button>
    </form>
  )
}
  • The markup. The server writes what the browser's own submit needs: method="post" action="/apply?qat-form=0" on the <form> (the number is the form's position on the page), and name, type, the schema's constraint attributes and the current value on each field.
  • Without JavaScript, the browser posts the form to that URL. The server renders the page with the posted values and validates them with the same schema: the browser's constraint-validation rules (required, type, pattern, minLength, min/max/step, …) and your validate functions.
    • Invalid: the page comes back (status 422) with f.errors filled, the values as typed, and aria-invalid on the fields. The messages are your schema's messages. Without one, the server uses Chrome's English message, while the browser shows its own localized one; give message for the same words on both sides.
    • Valid: your f.submit(handler) handler runs on the server. navigate(to) in it is the redirect (303), and f.setError(name, message) sends the page back with that error. Without either, the answer is a 303 back to the page (POST/redirect/GET), so a reload never submits twice. The handler gets the same plain values as in the browser: numbers for type: 'number', booleans for checkboxes.
    • Only the page's own post is taken; any other is refused with 403. When the browser sends Sec-Fetch-Site, it decides: same-origin only (a page's own post under Referrer-Policy: no-referrer says Origin: null and same-origin, and is taken; a sandboxed frame says null and cross-site). Without it (Safari before 16.4, a client that is not a browser), the Origin, else the Referer's origin, must be the app's own. null, or neither header, is refused.
  • With JavaScript, the page resumes and the same nodes become the reactive form: errors as the user types, focus on the first invalid field, and the handler runs in the browser with no page load. What the user typed before the page resumed is kept. A submit made before then is queued and replayed once the form has resumed.
  • One handler, both sides. The handler runs wherever the submit happens, so write it to run in both places: call your API through a module (applications.add), as a route load does, not window or localStorage. navigate() and f.setError() work in both places.

This is the default for public-sector forms and for any form that must work for everyone: render its route on the server and the form needs no JavaScript, as progressive enhancement (the GOV.UK Service Manual's rule for public services) asks. The one exception is @qatjs/form/offline: it sends its submissions itself, so its route stays 'client'.

The validation rules are tested to agree with Chrome's own, row by row, from one table (packages/server/test/form-validity.cases.js). The server side is @qatjs/server/form: a server build includes it when the app depends on @qatjs/form, and the browser gets none of it. The form core grows by 65 B for it (1.20 kB, pnpm size).

Offline forms

@qatjs/form/offline is a form(schema, options) that sends itself. With offline: true, a submission made without network waits in IndexedDB and is sent, in order, when the network returns:

.qx23 linesOpen in the playground
// contact.qx
import { form } from '@qatjs/form/offline'

export default function Contact() {
  let f = form(
    { email: { type: 'email', required: true }, message: { required: true } },
    {
      action: '/api/messages',
      offline: true,
      onSubmitted: (reply, values) => console.log('sent', values.message, reply),
      onFailed: (error, values) => console.log(error.status, error.message),
    },
  )
  return (
    <form novalidate on:submit={f.submit()}>
      <input ref={f.field('email')} />
      <textarea ref={f.field('message')} />
      <button disabled={f.submitting}>Send</button>
      {if (f.queued)}<p role="status">{f.queued} queued: sent when you are back online</p>{/if}
      {if (f.error)}<p role="alert">{f.error}</p>{/if}
    </form>
  )
}
  • f.submit() validates like the plain form, then sends the values as JSON to action (method defaults to 'POST'; headers are added). f.submit(handler) is still the plain form's submit.
  • Results go to onSubmitted(result, values) for a 2xx response (result is the JSON body, or its text), and to onFailed({ status, message }, values) for any other. message is the body's message, else its text. A 409 also sets f.error to that message: the server says the submission conflicts, so the form shows it. The next submit clears f.error.
  • Without network: when navigator.onLine is false, or fetch fails, the submission goes to the queue and f.queued counts this form's waiting submissions. The count stays right across a reload, and across tabs.
  • Replay, oldest first, under a Web Lock, so only one replayer runs at a time. A page replays on the online event, and at start when something is waiting. With a qatjs compress --pwa build, the service worker also replays on Background Sync, even with no page open. A replay stops at the first network failure, which keeps the order. Its results go to the callbacks of every open form with that name.
  • name (default: `${method} ${action}`) routes the results. queue replaces the IndexedDB store (idbQueue) with any { add, all, delete }, for tests.
  • Without offline: true, a network failure is onFailed({ status: 0, … }).
  • The queue keeps the whole request, its headers too, in IndexedDB in the clear, and replays it later as it was. Do not put a token in headers (an Authorization header would sit on the device and be sent after it may have expired): let a cookie carry the session, or the server answer the replay's 401 through onFailed.

The entry is separate: an app that does not import it pays nothing. The form core is 1.20 kB; @qatjs/form/offline adds about 0.94 kB.