Data sources
Fieldia has no backend of its own. A page's records and responses travel through a data source: an object your app writes, with up to eight methods. Implement only the ones your pages use.
interface DataSource {
load?(request: LoadRequest): Promise<Values | LoadedRecord>; // read a record: its values, or with its version and rights
save?(request: SaveRequest): Promise<SaveResult>; // create or update it
onchange?(request: OnchangeRequest): Promise<OnchangeResult>; // recalculate after a change
search?(request: SearchRequest): Promise<RelatedRecord[]>; // find records to link to
create?(request: CreateRequest): Promise<RelatedRecord>; // make one from a typed name
submit?(request: SubmitRequest): Promise<SubmitResult>; // store one response
list?(request: ListRequest): Promise<ListResult>; // a page of records, for a list
groups?(request: GroupRequest): Promise<Group[]>; // a list's groups and their counts
views?(request: ViewsRequest): Promise<SavedView[]>; // a list's views kept for the person and the team
saveView?(request: SaveViewRequest): Promise<SavedView>; // keep one: the person's own, or shared
deleteView?(request: DeleteViewRequest): Promise<void>; // delete one of the person's own
totals?(request: TotalsRequest): Promise<TotalsResult>; // a list's sums: under it, per group, the rows ticked
options?(request: OptionsRequest): Promise<Option[]>; // a selection's choices from the app
definitions?(request: OptionsRequest): Promise<PropertyDefinition[]>; // properties a linked record keeps
saveDefinitions?(request: OptionsRequest & { definitions }): Promise<void>; // one added in place
archive?(request: ArchiveRequest): Promise<void>; // archive a record, or bring it back
copy?(request: RecordRequest): Promise<SaveResult>; // duplicate it: the copy's id
delete?(request: RecordRequest): Promise<void>; // delete it
attachments?(request: RecordRequest): Promise<FileValue[]>; // its files, the main one first
upload?(file: UploadFile, request: UploadRequest): Promise<UploadedFile>; // store one file as it is picked
writeMany?(request: WriteManyRequest): Promise<WriteManyResult>; // one value in many records: a list's Edit
exportRecords?(request: ExportRequest): Promise<ExportedFile | { message } | false>; // a list's export, on the server
createMany?(request: CreateManyRequest): Promise<CreateManyResult>; // many new records at once: a list's Import
importRecords?(request: ImportRequest): Promise<{ message } | false>; // a list's import, on the server
slots?(request: SlotsRequest): Promise<SlotsResult>; // the times free to book, day by day
duplicates?(request: DuplicatesRequest): Promise<DuplicatesResult>; // records like the one typed
merge?(request: MergeRequest): Promise<MergeResult | void>; // two records into one
notDuplicates?(request: NotDuplicatesRequest): Promise<RecordId[]>; // those said to be someone new
markNotDuplicate?(request: MarkNotDuplicateRequest): Promise<void>; // one said to be someone new
limits?(request: LimitsRequest): Promise<LimitsResult>; // responses taken, this person's, each choice's takers
saveDraft?(request: SaveDraftRequest): Promise<SavedDraft>; // keep the answers so far, to continue later
loadDraft?(request: LoadDraftRequest): Promise<StoredDraft | null>; // a draft, by its key
approvals?(request: ApprovalsRequest): Promise<Approvals>; // a record's approval levels, what was decided, what this person may decide
decide?(request: DecideRequest): Promise<Approvals | void>; // approve or reject at a level, with why
suggest?(request: SuggestRequest): Promise<SuggestResult>; // AI: values for a form, from words or files
rewrite?(request: RewriteRequest): Promise<RewriteResult>; // AI: a text field drafted or polished
searchToFilter?(request: SearchToFilterRequest): Promise<SearchToFilterResult>; // AI: plain words as filters
clusters?(request: ClustersRequest): Promise<ClustersResult | false>; // a list's map: the view's bubbles, counted
sendCode?(request: SendCodeRequest): Promise<SentCode>; // send a code that proves an email or a phone
checkCode?(request: CheckCodeRequest): Promise<CodeChecked>; // check the code typed
pay?(request: PayRequest): Promise<PayResult>; // take a payment the answers wait for
templates?(request: TemplatesRequest): Promise<RecordTemplate[]>; // record templates people saved
saveTemplate?(request: SaveTemplateRequest): Promise<RecordTemplate>;
deleteTemplate?(request: TemplateRequest): Promise<void>;
subscribe?(record: RecordRequest, push: (change: RecordChange) => void): () => void; // changes made elsewhere
presence?(request: PresenceRequest, push: (people: PresentPerson[]) => void): () => void; // who else is here
}
| Method | Called when | Needed for |
|---|---|---|
load | A record page opens with a recordId | Editing an existing record |
save | Someone presses Save (or autosave fires) | Record pages |
onchange | A value changes, so the backend can fill in others | Totals, defaults that depend on other fields |
search | Someone types in a many2one, many2many or reference | Links to other records |
create | Someone picks Create “…” in a link field | Making a record without leaving the page |
submit | Someone sends a responses page | Surveys, sign-ups |
list | A list opens, is searched, sorted or paged | Lists of records — see lists |
groups | A list is grouped by a field, or a date by its month, quarter, week, day or year; a filter bar counts its values (filterCounts), a record of links under each of its links | Group By — see lists that add up; a filter's values with no counts — see filters |
views · saveView · deleteView | A list with a search bar opens, before its records; someone saves the search on screen, or deletes a view of their own | Views kept on your server — a search, an order and columns by name, the person's own and the team's, the same on every device; the list opens on the default one — see saved views; without views, favourites stay in the person's browser |
totals | A list totals a column: as it is searched, grouped, and as rows are ticked; its count says how many a named filter, a favourite or a phone's sheet finds | A totals row, sums on each Group By heading, the sum of the rows ticked — see lists that add up; without it, none shows, and a filter is counted by list's total |
options | A choice with optionsFrom is shown, and again when a field it changes with changes; a table's line's by that line's values, its record as parent, shared by lines alike | Choices from your own lists — a city by its country, a connection's tools on each line — see choices that follow another column |
definitions | A properties field with definitionsFrom is shown, and again when the link it follows changes | Properties a linked record defines — see business widgets |
saveDefinitions | Someone adds a property in place | Keeping it on that record |
archive · copy · delete | The gear menu's Archive, Unarchive, Duplicate or Delete, or those steps, run | The record's own operations — without one, your app's action of the step's name is called. See Around a record |
attachments | A sheet that shows the record's attachment beside it opens a record | The PDF or picture beside the sheet |
writeMany | Someone presses Edit for many records of a list, and says Yes; a block pasted on a list whose cells change in place gives several rows the same change | Changing many at once in one call — without it, the list saves each in turn. See many records at once and a list changed in place |
exportRecords | Someone exports a list | An export written on your server — without it, the browser writes it |
createMany | Someone imports a file's rows into a list | Making many records in one call — without it, the list saves each as a new record. See many records made at once |
importRecords | Someone has matched a file's columns, before its rows are checked | An import taken on your server, a file of any size — without it, the browser imports it |
upload | Someone picks or drops a file in a file or picture field, uploads a picture of a signature, or saves one drawn | Files kept in your store, the record holding only their links — see files stored as they are picked |
slots | A date and time drawn as booking slots shows a month, a field it depends on changes, or someone picks a time | Booking a time from those free — see booking slots |
duplicates | Someone stops typing in a field the page's duplicates names, a saved record opens, or a record is saved | Saying which records it may duplicate, under the field they matched on — see possible duplicates |
merge | Someone merges a record with one like it, a value picked for each field | Merge, beside a possible duplicate — without it, none is offered |
notDuplicates · markNotDuplicate | A saved record with possible duplicates is shown; someone presses It's someone new | What was let be kept on your server, so every device lets it be — without both, the person's browser keeps it. See possible duplicates |
limits | A page with limits or options with seats opens, and again just before its answers go and after | The most responses, one from each person, each choice's places left — see opening, closing and limiting a form; without it, a page keeps to its dates alone |
sendCode · checkCode | Someone presses Send a code under an email or a phone whose node says options.verify; types the code | Proof the person owns it, before the answers go — see proof of an email or a phone; without both, no field asks for a code |
pay | Someone presses Pay in a page's payment step, after its answers passed their checks | A reservation fee or a deposit taken through your own provider, before anything is sent — see a payment the answers wait for; without it, no payment is asked |
templates · saveTemplate · deleteTemplate | The Templates menu of a page with templates opens; someone saves a record as a template, or lets some go | Templates kept on your server, shared as you share them — see record templates; without them, the person's browser keeps their own |
subscribe · presence | A record is shown (once it has an id), and again as the person starts or stops changing it | Changes made elsewhere arriving in an open record, who else has it open — see live records; without them, a change elsewhere is found as a save meets it |
saveDraft · loadDraft | Someone types on a page with continueLater, enters a wizard's step, or presses Continue later; a page opens with a draft's key | Answers kept on your server, continued on any device — see save and resume; without them, no Continue later shows |
approvals · decide | A record of a page with approval is shown, saved, or decided on; someone presses Approve, or Reject with why | Who must approve it at which level, the record locked while it waits, Approve and Reject, its history — see approvals on a record; without them, nothing shows |
suggest · rewrite · searchToFilter | Someone presses Fill from text (a page's suggest), a text field's Draft or Polish (its rewrite), or ✦ beside a list's search (searchToFilter) | AI help by your own model, each value shown to accept or reject — see AI help; without one, what asks for it is hidden |
clusters | A list's map shows a search, and again a moment after it stops moving | Every record a search finds on the map, however many, as bubbles your server counts — see thousands on a map; without it, or answered false, the map loads at most 500 and gathers them itself |
What each method receives
load({ model, id, fields })— the page's fields come along, so you can read exactly the columns the page shows. Answer one record's values (orloadedRecord(values, { version, can })): a list — Odoo'sread()answers one, give its first — or an envelope round the record ({ data: … }) is refused as a failed load. Values are read as their fields hold them: a decimal sent as text, Odoo'sfalsefor empty, a link as[7, "Nile Traders"]or{ id, name }. One that cannot be read is said under its field and never sent back over what you hold. A failed load is said over the page with a Retry of its own; until a record's first load ends well its fields are inert and nothing of it is saved.save({ model, id, fields, changes, values })— to refuse it, throwsaveRefused({ kind, message, fields }): the fields, a business rule or the network, each shown where it belongs (see a save the server refuses).idisnullfor a new record.changesholds only what changed since the record was loaded;valuesholds everything, for backends that save whole records. A save made outside a form, such as a calendar's move, a timeline's bar moved or stretched, or its Undo, carriespartial: true:valuesandfieldsthen hold only the fields it changes, so a backend that saves whole records writes those and keeps the rest as stored. Return{ id }, andvaluesif your backend recalculated anything.onchange({ model, id, changed, values })— return{ values }for the fields to update, and an optionalwarning. The warning appears under the field that changed, without blocking, and goes away with the next answer that has none. A line edited in a dialog also asks it, with that line changed, to show what it would become; nothing is saved, so answer without side effects.search({ model, query, filter, limit })— the field's filter arrives with everyvalueFromalready replaced by its value, its groups kept: an{ any: [...] }is an OR, an{ all: [...] }an AND. Translate both, or the OR is lost;matchesFilter(values, filter)from@fieldia/corejudges a record the same way, for sources that filter in JavaScript. Return[{ id, label }]. Withexact: true, return only the records named exactlyquery, in any case: a box asks so for a name typed when a search's first answers, cut at theirlimit, did not hold it, and to tell two records of one name apart. A source that leavesexactout still works: the box looks for the name among what comes.- A
jsonfield whose widget names records of a model — an analytic distribution's accounts — searches thatmodeltoo, and asks for the records its value holds by their ids: the filter is then[{ field: "id", op: "in", value: [12, 14] }]. definitions({ list, values })— the definitions of a properties field'sdefinitionsFrom.list: those the record its link points to keeps (Flectra'sdefinition_record), read fromvalues.saveDefinitions({ list, values, definitions })keeps them all again, one added in place among them.create({ model, name })— make a record from just its name (a backend'sname_create). Return{ id, label }.submit({ pageId, values, bot })— the answers to the questions that were shown; skipped steps are left out.botcomes on a page with a bot check, below. Return{ id }— the reference you give the response,"B-1043"— and anyvaluesyou worked out as you kept it, by the page's fields (the time you confirmed): the page's ending reads them,{id}in its words saying the reference. On a quiz,quiz— the results you marked on your server — is shown in place of the page's own marking. A page that draws its questions sendsordertoo: by part, the ids of the parts this person was shown, in their order. The answers on the form stay as they were sent;form.getState().sentkeeps what you answered.
Every save and submit carries key: its idempotency key, made at its first try and the same for every try after — Retry after an answer lost on the way, a copy kept without signal and sent later — until it went (a new record's until it has its id, a response's until the form starts another). A request with a key you kept is the same send tried again: store its values over that one's and answer as you did, never a second record or response. form.save() asked twice with nothing changed is one save, and a response's answers are never sent twice as they were.
A slow answer is handled for you: if someone keeps typing, an onchange or search answer that arrives after a newer question is ignored.
Nothing waits for ever
Each request a person waits on — load, list, groups, save, submit, onchange, search, options — answers within the viewer's timeout (milliseconds, 30 000 unless you say, 0 for none), or ends as the network's problem, said where it was asked with Retry: a list's in its place, a record's at the top of the form, a save's in the banner over it. The deadline ends the request; a wait's loading.timeout ends its loader — where both are set, the sooner ends the wait, said once. Its signal aborts then: pass it to fetch to free your server sooner. A late answer is dropped, and Retry carries the first try's key, so you keep it once. A Discard waits for a save on its way at most 5 seconds, then ends it. A part or a language's words that do not come within 30 s settle as failed: the page draws without them.
async save({ model, id, changes, key, signal }) {
const response = await fetch(`/api/${model}/${id ?? ''}`, { method: 'POST', body: JSON.stringify({ changes, key }), signal });
return response.json();
}
What Fieldia keeps in the browser
Everything Fieldia keeps on a device is a person's, by whose it is: the signed-in person's (the viewer's user), else the tab's it was typed in — so the next person on a shared tablet is never offered the last one's typing, nor sends it under their own session.
- Drafts — in your
drafts.store(localStorage fits) asfieldia:draft:<owner>:<page>:<record|new>, a timed page's in the tab's own store: a record's draft keeps only the fields changed, with the version they were typed against — laid again on a record someone saved since, it is said as a conflict, never reverting their work — and never a secret field (a password box, or"secret": trueon a field: a PIN, an ID number). - The tab's id —
fieldia:tabin the tab's own store, while it is open. - Sends kept without signal — IndexedDB
fieldia-outbox: each with its owner, sent by their forms alone. - Preferences — localStorage
fieldia:<key>, a signed-in person's underfieldia:u:<id>:: a list's columns, its filters shown, favourites, saved record templates, the records picked last. - The designer —
fieldia.designer.mode,fieldia.designer.size,fieldia.designer.looks.
import { drafts, outbox } from '@fieldia/core';
async function signOut(userId) {
drafts.clear({ user: userId }); // or drafts.clear() for every draft on the device
await outbox.clear({ user: userId }); // their sends kept without signal, let go unsent
}
Your server is the final gate
Every rule a page holds — required, a pattern, a size, the options offered, a code proved, a payment taken, a time limit, one response each — is checked in the person's browser, and a request made by hand passes none of them. Run the same page's checks where its answers arrive, with checkSubmission from @fieldia/core, on the page as your server keeps it:
import { checkSubmission, saveRefused } from '@fieldia/core';
async function received(request, session) {
const { ok, errors, problems, values, due } = await checkSubmission(pages[request.pageId], request.values, {
verified: request.verified, // each proof present for the value sent: then check the proof is one you signed
payment: request.payment, // paid in full for what these answers owe (due): then check its reference with your provider
order: request.order, // a question not drawn for this person is not asked
user: { id: session.userId, roles: session.roles },
});
if (!ok) throw saveRefused({ kind: 'fields', message: problems[0] ?? 'Check the answers', fields: errors });
return store(values); // what the page works out, worked out here
}
It answers each field's problem in the page's words, what else is wrong (answers over maxBytes, 1 MB unless said; a field the page has not; a payment missing or short), the answers as the page's rules leave them, and what is due. What only your server can know stays yours: a proof's signature, a payment's reference, when it served the page, how many responses a person sent. In the browser, a part that guards a send — the payment step, the code check, a time limit's clock, a link's hidden fields, a record's approvals, options by condition, a text's languages, a page's limits — fails closed: where it could not load, nothing is sent and the form says which (The payment step could not load, so nothing was sent. Try again.), with Retry.
A public form's bot check
A page of responses anyone may send — a sign-up, a contact form — can check that a person sent it: botCheck draws a box no person sees, reaches with Tab or hears read out, which a bot filling every box fills (honeypot, on unless false); times the answers from the page shown to its send, against the fewest seconds a person takes (minSeconds, 3 unless said; 0 tells none); and holds the place for your app's own captcha — Turnstile, reCAPTCHA, hCaptcha — in a slot of the page (captcha, the slot's name).
"layout": { "type": "sections", "id": "signup", "children": [
…,
{ "type": "slot", "id": "s-captcha", "name": "captcha" }
] },
"botCheck": { "minSeconds": 3, "captcha": "captcha" }
Nothing is refused on the page for what it saw: submit gets it beside the answers, and so does the send event, and your app decides — keep the response aside, check the token with the captcha's service, or refuse it with saveRefused. A person whose browser filled every box in at once can be quick, which is why it is yours to judge.
async submit({ pageId, values, bot }) {
// bot: { honeypot: false, tooFast: false, seconds: 41.2, captcha: '0.Zx…' }
if (bot?.honeypot) return { id: await keepAside(pageId, values) };
if (bot && !(await verifyTurnstile(bot.captcha))) throw saveRefused({ kind: 'rule', message: 'Please tick the check box first.' });
return { id: await store(pageId, values) };
}
// The captcha's widget, in the page's slot: its token handed to the form, a new one after each send.
slots: {
captcha: (element, { form }) => {
const id = turnstile.render(element, { sitekey, callback: (token) => form.botCheck({ captcha: token }) });
const spent = form.on('send', () => turnstile.reset(id));
return () => (spent(), turnstile.remove(id));
},
}
A page without botCheck sends what it always did. In the designer, a page of responses has Bot check on its Rules tab. The sign-up demo has one, with a stand-in for a captcha, and shows under the form what the app was told.
Fields filled from the link
A form shared as a link — in a WhatsApp campaign, by a broker, beside a listing — can say who sent the person and what they asked about, with no code of your app's: prefill.fromUrl names the link's parameters, each filling the field of its name, or the field it names.
"prefill": { "fromUrl": ["utm_source", "utm_campaign", { "param": "agent", "field": "agent_code" }, "unit"] },
"fields": {
"utm_source": { "type": "char", "label": "Source" },
"utm_campaign": { "type": "char", "label": "Campaign" },
"agent_code": { "type": "char", "label": "Agent" },
"unit": { "type": "char", "label": "Unit" }
}
https://homes.example/enquiry?utm_source=whatsapp&utm_campaign=autumn&agent=mona&unit=B-12
Opened so, the form starts with those values — and again after Submit another. A field placed nowhere is a hidden field: seen by no one, sent with the answers to submit (or in a new record's save). One placed on the page shows the value, for the person to keep or change. Each is read as its field reads words — a number, yes/no/1/0, a choice by one of its options' values, a day as 2026-10-20, a day and time with its offset — and words that do not read so, or that the field's own checks would refuse, are left out: a hidden field no one can put right never stops a send. The link never writes over an answer: what the person types, and a draft opened over it, are theirs; a stored record opened is never filled. The form reads the page's own address unless it is given url — the React, Vue and Angular components take it too, for an app rendered on a server or embedded, whose address bar is not the link; a form shown in a partner's page through the embed script gets that page's campaign parameters passed on. In the designer, Filled from the link on a page's Rules tab names each parameter and the field it fills, or its own hidden field.
Proof of an email or a phone
A lead form pays for every fake number. A field drawn as an email or a phone whose node says options.verify asks the person to prove it is theirs before the answers go: Send a code under its box — one button for each way the page offers — then the code's box (autocomplete="one-time-code", so a phone offers the code from its message), Confirm, how long the code works and when another may be asked for. Right, the field says Confirmed; a send before that is refused under it (Mobile is not confirmed: send a code and type it in), and a number changed afterwards asks again. Fieldia sends nothing itself and holds no keys: your data source sends the code its own way — your mail service, Twilio, a WhatsApp gateway — and checks it.
{ "type": "field", "id": "f-phone", "field": "phone", "widget": "phone", "options": { "verify": { "by": ["whatsapp", "sms"] } } }
{ "type": "field", "id": "f-email", "field": "email", "widget": "email", "options": { "verify": true } }
async sendCode({ field, value, kind, by, language }) {
// value: "+201012345678" (a phone read the world over) or "mona@example.com"
const { id, expiresAt } = await myCodes.send(value, { via: by ?? (kind === 'email' ? 'email' : 'sms'), language });
return { id, expiresAt, retryAfter: 30, length: 6 }; // or throw saveRefused({ kind: 'rule', message: 'Too many codes: try in an hour' })
},
async checkCode({ value, code, id }) {
const result = await myCodes.check(id, value, code);
return result.ok ? { ok: true, proof: result.signedToken } : { ok: false, triesLeft: result.triesLeft, expired: result.expired };
},
async submit({ values, verified }) {
// verified: { phone: { value: "+201012345678", proof: "eyJ…" } } — trust a value only by its proof
if (!(await myCodes.trusts(verified?.phone))) throw saveRefused({ kind: 'fields', message: 'Confirm your mobile', fields: { phone: 'Confirm your mobile' } });
return { id: await store(values) };
}
Each send — submit, or save on a record's page — carries verified: the values proved and your proof of each, so your server trusts a value only by a proof it signed. form.getState().verified holds them; form.joined('verify').asks(field) says whether a field asks for one, form.joined('verify').mark(field, { value, proof }) keeps one your app proved its own way. In the designer, an email's or a phone's settings have Confirmed by a code, and a phone's the ways it is sent. The enquiry demo sends its codes to a stand-in phone over the form.
A payment the answers wait for
A reservation fee, a deposit, a retainer: a page's payment is taken before its answers go, through your own provider — Stripe, Paymob, Fawry, PayPal — with no key and no provider's code in Fieldia. Submit checks the answers first, then the payment step shows what is due and Pay; nothing is sent until it is paid.
"payment": {
"label": "Reservation fee",
"amount": 10000,
"currency": "EGP",
"when": "visit == 'reserve'",
"description": "Held for 7 days and taken off the price; refunded if the unit is no longer available."
}
amount is a number, or a number or money field's name; currency a code, or a field holding one — left out, a money field's own; when, a condition on the answers. Your data source's pay is called inside the person's press of Pay, so it may open the provider's checkout in a window of its own, or draw it in request.slot, the payment step's own place for it:
async pay({ pageId, values, key, slot, signal }) {
// key: the same for every try of this response's payment — your provider's idempotency key.
// The amount is worked out on your server from the answers: the browser's is the person's to change.
const session = await myServer.checkout({ pageId, values, key });
const result = await myProvider.mount(slot, session, { signal }); // or window.open(session.url) and wait for its webhook
return result.ok ? { status: 'paid', reference: result.id } : { status: result.cancelled ? 'cancelled' : 'failed', message: result.error };
},
async submit({ values, payment }) {
// payment: { amount: 10000, currency: 'EGP', key: 'pay-…', reference: 'pi_3Q…' } — checked on your server, below
return { id: await myServer.send({ values, payment }) };
}
// On your server, with the page as you keep it — never the amount, nor the page, the browser sends.
import { checkSubmission } from '@fieldia/core';
async function checkout({ pageId, values, key }) {
const { due } = await checkSubmission(pages[pageId], values);
if (!due) throw new Error('Nothing is due for these answers');
return myProvider.createSession({ amount: due.amount, currency: due.currency, idempotencyKey: key });
}
async function send({ values, payment }) {
const check = await checkSubmission(pages['enquiry'], values, { payment });
if (!check.ok || !(await myProvider.paid(payment.reference, check.due))) throw saveRefused({ kind: 'rule', message: 'The payment does not cover these answers' });
return store(check.values, payment);
}
A page whose amount is a field its link fills (prefill) is warned of in its checks: anyone can change an address. Paid, the answers go with payment; failed or cancelled, the step says nothing was sent, with Pay again and Back to the answers. A send that fails after paying is sent again without paying twice, and every send path — Ctrl+Enter, a wizard's finish, your own form.save() — waits for the payment the same way. In the designer, Payment before sending on a page's Rules tab. The enquiry demo reserves a unit through a stand-in for a provider's checkout.
Sends kept without signal
A broker at a viewing in a compound, an inspector in a basement, a courier at a door: "outbox": true keeps a send that finds no network on the device — its answers, its photos' bytes — and sends it when the signal comes back. No new member: what your source already has (submit, save, upload) takes it then.
{ "id": "viewing-report", "data": { "kind": "responses" }, "outbox": true, … }
A failure that reads as the network's — a TypeError from fetch — is kept in the browser's IndexedDB (never lost on a reload, shared by your site's tabs) and said: the form ends Kept on this device, and a bar over it says how many sends wait, with Send now. They go in order when the browser says it is online, every half a minute while something waits, as the page opens, and right after a send that went through (which goes first); each is taken by one sender only (its claim renewed while it goes, so a long upload is never sent by a second tab), and carries the key of its first try — key, and queued: { key, at } — so your server keeps it once. A save of a record with sends of it kept sends those first, and goes after them, each at its version now. Where the browser keeps nothing past the page (no IndexedDB), the form says so — keep the page open — never Kept on this device. A photo taken without signal is stored through upload just before its send goes. A send your server refuses then is kept, said, and offered Try again and Discard. A record saved again while its first save waits is saved once, as it is now, and takes its id when it went. Give the viewer outbox — a store of your own (list, put, delete, claim) — to keep them elsewhere. In the designer, Without signal on a page's Rules tab. The viewing report demo works offline at a press, or with your connection really off.
Fieldia's outbox keeps the sends. Opening the page with no signal — a reload in the compound, the phone in airplane mode — is your app's service worker's: without one, the browser has nothing to show. A small one does it: it keeps the page and every script, sheet and part it loaded, and serves them only when the network fails, so online the page is always the newest. The viewing report demo has one (offline-sw.js), its scope that page alone:
// sw.js — network first; what came kept for the day there is no signal.
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith(
fetch(event.request).then(
(response) => {
const copy = response.clone();
if (response.ok) event.waitUntil(caches.open('app').then((cache) => cache.put(event.request, copy)));
return response;
},
async (failed) => (await caches.match(event.request)) ?? Promise.reject(failed)
)
);
});
// The page: Fieldia's parts come as the page first uses them, so let it be opened once online.
navigator.serviceWorker.register('/sw.js', { scope: '/reports/' });
What the page loaded before its worker was there — its first visit — is not kept unless the page tells the worker (the demo posts it the addresses the browser loaded: performance.getEntriesByType('resource')), or a build tool lists them for it (Workbox, vite-plugin-pwa).
Files stored as they are picked
A phone's photo is 3 to 12 MB. Twenty of them inside one save fail on mobile data, and one in a draft fills the browser's store. Give your data source upload, and a file or picture field sends each file to your store as soon as it is picked: photos are made smaller first, each shows on its way with a bar, × to cancel it and Retry when it failed, and the field keeps only what upload returns — { url, name, size, type, fileId }, never the bytes. Three go at once, the rest wait their turn; a field of several keeps them in the order they were picked.
upload(file, { model, field, recordId, line, signal, onProgress })—fileis the browser'sFile(made smaller already, for a photo).recordIdisnullwhile the record is new: keep the file, and link it when the record's first save carries the field's{ url, fileId }.linenames a table's line,{ field, key, id }, for a file on one. On a page of responses (a survey),modelis the page's id. In a saved form placed in a record (aformpart), the file is the record's:modelandrecordIdare the record's, andfieldsays where it sits in the answers the record keeps under the part's name —consent.deed, orconsent.roomsfor a table's line.- Call
onProgress(sent, total)as the bytes go, for the bar's number; without it the bar moves with none. - To fail, throw: the field says the file was not uploaded and offers Retry. Throw
saveRefused({ kind: 'rule', message })when your store will not keep this file — its kind, its size — and the field shows your words, with no Retry, since trying again cannot help. - When
signalaborts — the person pressed ×, discarded their changes, or left — stop, and reject with an error namedAbortError: the file is dropped without being called a failure. - Save waits and tells. Pressed while files are still going, Save waits for them, saying where Saving… would be: “2 files still uploading. Saving when they are done.” A file that failed stops the save under its field — “balcony.jpg was not uploaded: try again, or remove it” — until it is sent again or taken away; once it is, the form no longer says it was not saved. Save shows as soon as a file is picked, before it has arrived. A saved form placed in the record is waited for, and stopped for, the same way.
- A file picked while a save is on its way was not in that save: it stays a change, shown and still to save, even when it is stored before the save returns.
- Bytes still in the record are stored by the save: a signature drawn on its pad, or a file your app set with its
data. A record's stored files that did not change are never sent again. - A draft never keeps a file's bytes: a field holding one is left out of the draft, a saved form's placed in the page too, and its record's value stays when the draft is restored.
- Without
upload, a file travels inside the record as base64, and a draft keeps it, as they always have; one larger than a megabyte warns once in the console.
Photos are made smaller by the field's shrink — see files and photos.
uploadTo: a plain endpoint
uploadTo from @fieldia/core writes upload for you. It sends through XMLHttpRequest, so the bar has its number, and through fetch where there is none. By default it POSTs a form with the file under file, and reads the stored file's address from the answer's JSON url (and its id as fileId), else from its Location. An answer of 400, 409, 413, 415 or 422 is a refusal, shown in the server's words (its JSON's message); any other failure offers Retry.
import { uploadTo } from '@fieldia/core';
const dataSource = {
...yourDataSource,
upload: uploadTo({
url: '/api/files', // or (file, request) => an address of the file's own
headers: { 'X-CSRF-Token': csrfToken }, // or (file, request) => headers
field: 'file', // the form's field the file goes under
// link: (answer, file) => ({ url: answer.json.location }), // when your answer says it its own way
}),
};
Straight to Azure Blob storage
The file need not pass through your server. Your server signs one address per file — a service SAS, write-only, for minutes — and the browser PUTs the file to it. The field keeps the blob's address, without the signature. No SDK on either side:
// In the page: ask your server for the address, then PUT the file there.
const upload = uploadTo({
method: 'PUT',
url: async (file) => (await fetch(`/api/upload-address?name=${encodeURIComponent(file.name)}`)).text(),
headers: { 'x-ms-blob-type': 'BlockBlob' },
});
// On your server (Node): the address, signed with the storage account's key.
import { createHmac, randomUUID } from 'node:crypto';
const ACCOUNT = 'yourstorage';
const CONTAINER = 'listings';
const KEY = process.env.AZURE_STORAGE_KEY; // the account's key, base64, as the portal gives it
export function uploadAddress(fileName) {
const blob = `${new Date().toISOString().slice(0, 10)}/${randomUUID()}-${fileName.replace(/[^\w.-]+/g, '-')}`;
const expiry = new Date(Date.now() + 10 * 60_000).toISOString().replace(/\.\d+Z$/, 'Z');
const version = '2022-11-02';
const signed = [
'cw', '', expiry, `/blob/${ACCOUNT}/${CONTAINER}/${blob}`, // permissions, start, expiry, resource
'', '', 'https', version, 'b', // identifier, IP, protocol, version, a blob
'', '', '', '', '', '', '', // snapshot, encryption scope, and the five response headers
].join('\n');
const sig = createHmac('sha256', Buffer.from(KEY, 'base64')).update(signed, 'utf8').digest('base64');
const query = new URLSearchParams({ sv: version, spr: 'https', se: expiry, sr: 'b', sp: 'cw', sig });
return `https://${ACCOUNT}.blob.core.windows.net/${CONTAINER}/${blob}?${query}`;
}
Let your site PUT to the account in its CORS rules, with the x-ms-blob-type and Content-Type headers. To show a stored file to people who may not read the container, give them a read SAS for it when your server sends the record. An S3 presigned PUT URL works the same way, without the x-ms-blob-type header.
Booking slots
A date and time drawn as slots books a time from those your app has free: a month whose days are shaded by how they are booked, beside the chosen day's free times. Give your data source slots; without it, the field is the plain date and time box.
slots({ model, field, recordId, schedule, from, to, timeZone, length, between, values })— the daysfromandto(both included,"2026-10-01") are days intimeZone: the field's, its page's, or the browser's.scheduleis what the node'soptions.schedulenames (a doctor's, a showroom's), else the field's name;lengthandbetweenare the minutes a booking lasts and those kept free between two, as the page says.recordIdis the record booked: its own time is free to it.valuesholds every value of the form — the doctor, the car.- Answer
{ days, length }: each day by its date,{ state: 'open', free: ['2026-10-19T07:00:00Z', …] },{ state: 'full' },{ state: 'closed' }or{ state: 'holiday', note: 'Staff training day' }— a day left out is closed — and, when your server knows better than the page, the minutes a booking lasts (a service's own length). The free times are instants: in UTC, or with their offset. - It is asked a month at a time, again when a field in
options.dependsOnchanges or a page of responses sends a booking (Book another is never offered the time just booked), and once more for the day of a time picked: a time someone else booked meanwhile is said — “10:00 was just booked by someone else” — and the day's times drawn again; nothing is booked over. To fail, throw: the picker says so, with Try again. - The time picked is the field's instant; with
options.endField, the booking's end — its start and its length — goes there too. Yoursavestill decides: refuse a time taken by then withsaveRefused({ kind: 'rule', message }).
const dataSource = {
...yourDataSource,
async slots({ schedule, from, to, timeZone, recordId, values }) {
const query = new URLSearchParams({ schedule, from, to, timeZone, car: String(values.car?.id ?? '') });
if (recordId !== null) query.set('booking', String(recordId));
const answer = await fetch(`/api/test-drives/free?${query}`);
if (!answer.ok) throw new Error(await answer.text());
return answer.json(); // { days: { '2026-10-19': { state: 'open', free: [...] }, ... }, length: 45 }
},
};
form.findSlots(field, { from, to }) asks it for a widget of your own, the record, its values and the zone filled in; form.canFindSlots() says whether the source has it. For demos and tests, scheduleSlots answers from booking schedules, beside the memory data source.
Possible duplicates, and Merge
A record's page may say which fields records like the one typed are found by — the same phone, email or tax id, a name close enough — with duplicates. While someone types in one of them, a moment after they stop (and as a saved record opens, and as the record is saved), Fieldia asks your data source's duplicates; each record it answers with is said under the field it matched on — “A record with this Phone already exists: Nile Traders” — with Open it, It's someone new and, on a saved record where the source has merge, Merge…. Without duplicates in the source, nothing is asked and nothing shows.
"duplicates": { "fields": ["name", "phone", "email", "vat"] }
"duplicates": { "fields": ["phone", "email"], "on": "save" }
duplicates({ model, recordId, values, fields })—fieldsare those the page names that hold a value now (none: nothing is asked),valuesevery value of the form (a phone as E.164 where the page reads phones the world over),recordIdthe record typed (null while new) — never its own duplicate. Answer{ matches: [{ id, name, why: ['phone', 'email'], score? }] }:whynames the fields it matched on — the note goes under the first of them in sight, and a name field in it is said as “a name like this” where the names are not the same — andscore, from 0 to 1, puts the likest first. To fail, throw: nothing is said.on:'type'(the default) asks as the fields are typed in, as a saved record opens and as it is saved;'save'only as it is saved. Typing on leaves an answer on its way unheard; an answer for a record no longer shown is laid nowhere. Nothing is in Save's way: a duplicate is said, and Save saves — unless yoursaverefuses it.- Open it shows the record found in the form's place, once the person said Discard to what they typed (every change counts, as a panel's Escape counts it). It's someone new lets the record found be for this record, whatever field matches it next — a name typed after the email that found it — remembered for the record, by its id once saved: on your server where your source has
notDuplicatesandmarkNotDuplicate, else in the person's browser (the viewer'spreferences). - Kept on your server.
notDuplicates({ model, recordId })is asked as a saved record is shown, before its possible duplicates are said — answer with the ids of the records said to be someone else for it — andmarkNotDuplicate({ model, recordId, matchId })as the person presses It's someone new on a saved record, or saves a new one after pressing it (once for each). Keep them as pairs: Nile Traders is someone else for Nile Traders Co. as much as the other way round. A second device, a phone after the laptop, then never says a match let be on the first. Yourduplicatesneed not leave them out: the page does. Throw fromnotDuplicates, and the matches are said as found; throw frommarkNotDuplicate, and the browser keeps that one instead. What a browser kept before your source had them is still read. - On a page that names its records (
"records": { "one": "customer", "other": "customers", "a": "a customer" }, see the page), each match says them — A customer with this phone already exists: Nile Traders, It's a new customer, Merge two customers — its field's label small inside the sentence where the page says so ("lowerLabels": true). - Merge… saves what is typed first, reads the record found (
load), and shows the two side by side: the record kept picked over its column (the one found, unless the person picks this one), and a radio for each field they hold apart, the kept record's value picked — or the other's where the kept one holds nothing. What will happen is said before Merge. Thenmerge({ model, keepId, mergeIds, values, fields }): keepkeepIdwithvalues, the value picked for each field, and takemergeIdsaway. Moving what was theirs — messages, activities, the records linking to them — is your source's work. Refuse withsaveRefused({ kind: 'rule', message }): it is said in the screen, which stays. Merged, the record kept is shown, and{ message }answered is said with it.
const dataSource = {
...yourDataSource,
async duplicates({ model, recordId, values, fields }) {
const answer = await fetch(`/api/${model}/like`, { method: 'POST', body: JSON.stringify({ except: recordId, values, fields }) });
return answer.json(); // { matches: [{ id: 7, name: 'Nile Traders', why: ['phone'], score: 1 }] }
},
async merge({ model, keepId, mergeIds, values }) {
const answer = await fetch(`/api/${model}/${keepId}/merge`, { method: 'POST', body: JSON.stringify({ mergeIds, values }) });
if (answer.status === 403) throw saveRefused({ kind: 'rule', message: await answer.text() });
return answer.json(); // { message: '4 messages and 2 orders moved' }
},
async notDuplicates({ model, recordId }) {
const answer = await fetch(`/api/${model}/${recordId}/not-duplicates`);
return answer.json(); // [3, 17]
},
async markNotDuplicate({ model, recordId, matchId }) {
await fetch(`/api/${model}/${recordId}/not-duplicates`, { method: 'POST', body: JSON.stringify({ matchId }) });
},
};
form.findDuplicates() asks it for a screen of your own, and form.merge({ keepId, mergeIds, values }) merges; form.canFindDuplicates() and form.canMerge() say whether the page and its source can; form.notDuplicates() and form.markNotDuplicate(matchId) read and keep what was let be for the record shown, where form.keepsNotDuplicates() says the source has both. For demos and tests, alikeRecords() answers from the memory data source's records.
Opening, closing and limiting a form
A page of responses — a sign-up, a vote, a limited offer — may say when it takes answers and how many, with limits; and any choice may say how many may pick each option, with seats. A closed form says so as it opens, in place of its questions — “This form opens on 1 Nov 2026, 09:00.”, “This form closed on 20 Nov 2026.” (each day as the page's date boxes write it: its look.dateOrder, its language, its clock), “This form has all the responses it takes.”, “You have sent your answers to this form already.” — with the page's own message under it: a person learns it before typing anything, never after filling it in.
"limits": {
"opens": "2026-11-01T09:00",
"closes": "2026-11-20",
"maxResponses": 200,
"onePerPerson": true,
"message": "Missed it? Write to events@example.com."
},
"session": { "type": "selection", "label": "Session", "options": [
{ "value": "morning", "label": "Morning workshop", "seats": 30 },
{ "value": "afternoon", "label": "Afternoon workshop", "seats": 25 }
] }
opensandclosesare read on the page's clock (itstimeZone, the browser's without one): a day and a time, or a day alone — opening at its first minute, closing at its end, so the form takes answers through that day — or an instant with its offset. They need nothing of your source. A form left open as it opens or closes says so then; answers typed when it closed stay on screen, a banner saying they can no longer be sent, and are refused as they go.limits({ pageId, model, recordId, fields, user })— answer{ responses, mine, perChoice }: the responses sent so far (whatmaxResponsescounts), this person's (whatonePerPersoncounts — know them by your own sign-in;useris what the app told the form), and for each field infields, by option value, how many hold it — the record edited (recordId) not counted against itself. It is asked as the page opens — its questions wait while it is, where the page counts responses — again just before the answers go, and after. A part you leave out is not kept to; throw, and the page keeps to its dates alone.- An option with
seatsshows its places left beside its words — “3 left”, and “Full” once none are — in radios, checkboxes, the browser's list, picture cards, Fieldia's own list, a list that searches and tags. A full option is shown, never hidden: picked, it is refused under its question (“Afternoon workshop is full”), the choice kept as it was. One that filled up while it was held — someone else took the last place — stops the send: “Morning workshop is full now: choose another”. Options from your lists (optionsFrom) may carryseatstoo. - Your
submit(orsave) still has the last word: two people may press Submit for the last place at once.
Save and resume on another device
A long form — a patient's intake, a job application, an enquiry in several steps — is often started on a phone and finished on a laptop. A page with continueLater keeps its answers on your server as they are typed, through saveDraft, and offers Continue later: the answers kept, and the link your app makes to carry on from. The link opens the form where it stopped — its wizard's step, its answers, and text typed that did not read yet, kept as typed and said again.
const dataSource = {
...yourDataSource,
async saveDraft({ pageId, key, draft, later }) {
const answer = await fetch(`/api/drafts/${key ?? ''}`, { method: key ? 'PUT' : 'POST', body: JSON.stringify({ pageId, draft, later }) });
const { id } = await answer.json();
// Continue later: the link to carry on from, which your app may email too.
return later ? { key: id, link: `https://clinic.example/intake?resume=${id}`, message: 'We emailed you the link.' } : { key: id };
},
async loadDraft({ key }) {
const answer = await fetch(`/api/drafts/${key}`);
return answer.ok ? answer.json() : null; // { values, step, skipped, unread, answered, savedAt }
},
};
// The page opened from the link: its key, as the viewer's (or a wrapper's) resume.
mountViewer(element, { page, dataSource, resume: new URLSearchParams(location.search).get('resume') ?? undefined });
saveDraft({ pageId, model, recordId, key, draft, later })— kept a moment after typing stops, as a wizard's step is entered, and on Continue later (later: true). One at a time: the first carrieskey: nulland you answer with the key; each next carries it.draftholds the answers (values), thestepand the steps passed over (skipped), text typed that does not read (unread: by its box, as typed, with why), the fields the personansweredandsavedAt— the partial answers are yours to see: where people stopped, what they wrote.loadDraft({ pageId, key })— the draft, ornullwhen there is none (sent, gone): the form then starts empty and says so. A draft that comes after the person started typing is offered, never laid over what they typed.- The send carries the draft's key (
submit({ …, draft }),save({ …, draft })): let it go, or mark it sent. Where the app gives the viewer adrafts.store(the browser'slocalStorage), it keeps only the key, so the same browser finds the draft again; a server that fails keeps the draft there instead. - Without the two members, no Continue later shows, and drafts stay in the browser's store as they always have (with their step now).
form.continueLater(),form.canContinueLater()and the form'sdraftevent (onDraftin React,@draftin Vue,(draft)in Angular) are there for a screen of your own.
Approvals on a record
A purchase order over a limit, an expense, time off, a discount, a legal sign-off: a record that must be approved before it goes on. A page with approval says on the record where it stands — “Waiting for Finance: Mona Adel or Hany Lotfy”, “Needs approval from Finance, then CFO”, “Approved”, “Rejected by Mona Adel (Finance)” with why — its levels in their order with who decided there, Approve and Reject for those who may decide (Reject always asks why), the record locked while it waits but for the fields the page leaves open, each lock saying why, and its history: who asked, who decided, when, and why — beside the record and in its conversation. Fieldia says it and asks; who is asked, and in what order, is your app's to decide, or the approval engine's behind it.
"approval": { "open": ["notes"] }
const dataSource = {
...yourDataSource,
// The record's route as your engine has it: its levels, each with its people and where it stands.
async approvals({ model, recordId, user }) {
const route = await fetch(`/api/approvals/${model}/${recordId}`).then((answer) => answer.json());
return {
levels: [
{ id: 'finance', name: 'Finance', approvers: [{ id: 21, name: 'Mona Adel' }, { id: 28, name: 'Hany Lotfy' }], state: 'waiting' },
{ id: 'cfo', name: 'CFO', approvers: [{ id: 26, name: 'Sara Nabil' }], needs: 'all', state: 'later' },
],
history: route.history, // [{ decision: 'requested' | 'approved' | 'rejected' | 'notNeeded' | 'changed', level?, by, at, reason?, changes? }], oldest first
mine: route.mine, // the level ids this person may decide now: ['finance']
why: 'Orders over EGP 150,000 go to Finance, then the CFO.',
};
},
// A decision taken: your engine moves the record on; answer with the approvals as they stand, or nothing.
async decide({ model, recordId, level, decision, reason }) {
await fetch(`/api/approvals/${model}/${recordId}/${level}`, { method: 'POST', body: JSON.stringify({ decision, reason }) });
},
};
approvals({ model, recordId, user })— asked as a saved record is shown, after each save (a save may send it for approval), and after each decision. Each level comes with itsstate—waiting,later,approved,rejectedorskipped— and itsapprovers, each with what they decided in this round;needs: "all"where every one of them must approve (“Mona Adel and Omar Said”), any one by default (“… or …”);together: truewhere the levels are asked at once. No levels: the record needs no approval, and nothing shows. Throw, and the page says it could not read them, with Retry.decide({ model, recordId, level, decision, reason, user })—decisionisapprovedorrejected; a rejection always carries why. What is typed is read and saved first, then the record is loaded again after it — your decision may have moved it on. Refuse withsaveRefused({ kind: 'rule', message }): nothing is decided, and your words are said. Withoutdecide, the page says where a record stands and offers no Approve or Reject.- While a level waits, every field is locked but those
approval.opennames;"lock": falselocks none, and yoursaverefuses what it must. Rejected or approved, nothing is locked by it. - A trail of changes on the way to approval: a
changedentry of the history —{ decision: 'changed', by, at, changes: [{ field, label?, from, to }] }— says who changed the record while it waited for a decision, or after a rejection, and what: the band shows “Karim Fathy changed it” with each field from what to what, written as the page writes it, and the chatter beside it a tracked change. Your server records it as the save lands, by the person its sign-in knows — a save carries no person, and Fieldia never claims who saved — and answers it inhistory; the demos' memory source keeps one as such a save lands. Who may change a rejected record at all is the page's rule (a field'sreadonlyby condition, your source'scan). - The lock is the record's page's. A list whose cells change in place knows nothing of approvals: there a record that waits is locked only through the
can.edityour source gives its row ({ edit: false }while it waits), as your server refuses its save. - With Fieldia's chatter beside the record (
chatterSlot), the history is told among its messages, as events never posted to your chatter's source —chatterSlot({ source, approvals: false })where your server posts each decision there itself. - The routing we recommend, and the demos' memory source keeps: no one approves what they asked for — the person who sends a record for approval is none of that round's approvers (left out of the levels'
approversand ofmine, anddeciderefuses them), so a manager who sends his employee's claim again does not approve it himself; and a record whose rules ask no level moves on at once — sent, it takes its approved state, its history arequestedthen anotNeeded, and the page says “No approval needed” — never left “To approve” waiting for no one. - An engine such as Flowyard's approval step answers them from a record's run: each approval step on its way a level — not reached
later, waiting for its peoplewaiting, gone on its Approved wayapproved, its Declined wayrejected, on a branch not takenskipped, on parallel branchestogether—decideanswering the waiting step for the person, and its run's steps as they went thehistory; the run's starter left out of every approval step's people, and a run that reaches no approval step gone on by its Approved way at once (notNeeded). form.decide(level, decision, reason?),form.refreshApprovals(),form.approvalLock(field)andstate.approvalare there for a screen of your own.
AI help: values proposed, words written, a search read
Your app's own model fills a form from an e-mail or a message, drafts and polishes a text field, and turns a search typed in plain words into filters — through three members of your data source. Fieldia ships no model and no keys, and sends nothing anywhere but to your source. What it adds is the part every AI-first app builds again: every value proposed is shown on its field before it is kept — the value it would take the place of struck through, the new one, Accept and Reject, a table's lines to add listed under it — and over the form how many, your model's why, Accept all and Reject all. Nothing is written until it is accepted, and Undo puts back what was there.
"suggest": { "label": "Fill from an e-mail", "fields": ["name", "email", "phone", "website", "country_id", "child_ids"] }
"suggest": { "label": "Fill from their message", "fromField": "message", "fields": ["kind", "district", "budget", "bedrooms"] }
{ "type": "field", "id": "f-reply", "field": "reply", "options": { "rewrite": ["draft", "polish"] } }
{ "type": "list", "id": "homes", "columns": ["name", "kind", "district", "price"], "searchToFilter": true }
const dataSource = {
...yourDataSource,
// Fill from text: the words pasted (or a field's own, fromField), files picked, the page and the fields to fill.
async suggest({ page, values, fields, from, language }) {
const answer = await fetch('/api/ai/fill', { method: 'POST', body: JSON.stringify({ page, values, fields, text: from.text, language }) });
return answer.json(); // { values: { name: 'Amman Fresh Markets', country_id: 'Jordan', child_ids: [{ name: 'Lina Haddad' }] }, why }
},
// Draft and Polish (and a tool of your own, by its how).
async rewrite({ field, how, text, values, language }) {
const answer = await fetch('/api/ai/write', { method: 'POST', body: JSON.stringify({ field, how, text, values, language }) });
return answer.json(); // { text, why? }
},
// A search in plain words: conditions on the fields asked.
async searchToFilter({ text, fields, page }) {
const answer = await fetch('/api/ai/search', { method: 'POST', body: JSON.stringify({ text, fields, page }) });
return answer.json(); // { filter: [{ field: 'kind', op: '=', value: 'villa' }, { field: 'price', op: '<=', value: 15000000 }], why }
},
};
suggest({ pageId, model, recordId, page, values, fields, from, language })—fieldsare those the page'ssuggest.fieldsnames, else every field shown that the person can set;from.textthe words pasted, or those of the fieldsuggest.fromFieldnames (a buyer's message, a visit's notes, read at a press with no box to paste in);from.filesfiles picked. Answer{ values, why? }: each value as its field holds one — a link as{ id, label }or by its name, looked for exactly as a name typed is; a choice by its value or label; a table of lines' as the lines to add.rewrite({ field, how, text, values, … })—howisdraft(write it from the record),polish(make the words there clearer, offered once there are some), or thehowof a tool of your own,{ "how": "formal", "label": "More formal" }. Answer{ text, why? }: shown under the field in full.searchToFilter({ text, fields, page, … })— answer{ filter, text?, why? }: conditions on the fields asked (=,in,>=,<=,between,containsfor links,ilikefor words), each made a filter of the list's own kind — a chip, or the filter bar's values and ranges — andtext, words left to search for as typed. Undo puts the search and the words back.- The person comes first. A proposal is for the record it was asked for: another record shown, or Discard, and it goes; an answer that comes late is laid nowhere. A field typed in while it was asked keeps what was typed (“Left as you typed: Email”), and typing in a field with a proposal lets it go. A value that does not read as its field holds one — a name no record has, a choice not offered — is not used, and said.
- Your agent's own values, worked out elsewhere:
handle.propose({ city: 'Amman' }, { why: 'From the last call' })shows them the same way, with no member needed. - A text in several languages, one language at a time. A field with
translateis filled in the language its switch shows, else the reader's:suggestis told which by field (languages: { title: 'en' }) — answer that language's text alone — andrewritegets that language's words (language). The proposal says it (Proposed in English); the other languages stay as they were — each typed by a person, never translated by a machine. - What is never asked. Fill from text asks for the kinds a proposal fills alone — words, numbers, money, yes or no, a choice, a day, links, a table's lines: never a file, a picture or a photo set. A field scanned into with the camera takes a proposal as any text does.
What a save sends
changes.values has the plain fields that changed. Tables of lines and many2many links come as operations, named the way Odoo names its x2many commands, so an Odoo or Flectra adapter maps them one to one:
changes.lines['child_ids'] = [
{ op: 'create', key: 'new-1', values: { name: 'Sara' } },
{ op: 'update', id: 7, values: { email: 'sara@example.com' } },
{ op: 'delete', id: 9 },
];
changes.links['tag_ids'] = [{ op: 'link', id: 3 }, { op: 'unlink', id: 4 }]; // or { op: 'set', ids }, { op: 'clear' }
A text kept in several languages
A field with translate (one text in several languages) holds an object of each language's text, { "ar": "…", "en": "…" }, a language not typed yet left out — what load, list and save carry, as any value. No new method: three things are yours to do.
- Keep each language as typed. A server that keeps translations apart — Flectra's translated fields (
get_field_translations,update_field_translations), a column per language — builds the object as it loads and splits it as it saves. A plain text loaded for such a field is read as its first language's: nothing is lost, and the form saves the object once it is changed. - Find it in any of its languages. A search's
ilike,like,=,startswithon such a field holds where it holds in one of them, so a buyer's villa and فيلا find the same listing; a link's name searched in either finds its record. - One text where one is said. A list may give the object, and the page shows each row in its reader's language, another's marked; or it may give the reader's text alone, which the page shows as it is. A link's
labeland a list's order are your server's to read in its person's language — the memory source'slanguageoption does so.
Two people, one record: versions and conflicts
When two people open the same record and both save, the second save would wipe out the first without a word. A source that keeps versions stops that. Its load returns the record with the version it was read at, through loadedRecord; the form sends that version back with each save, as version, and keeps the one each save returns. When the record changed in between, the source throws a ConflictError naming who changed it, when, and — if it can — the record as they left it:
import { ConflictError, loadedRecord } from '@fieldia/core';
const dataSource: DataSource = {
async load({ model, id }) {
const row = await api.read(model, id);
return loadedRecord(row.values, { version: { token: row.etag, by: row.changedBy, at: row.changedAt } });
},
async save({ model, id, changes, version }) {
const response = await api.write(model, id, changes.values, { ifMatch: version?.token });
if (response.status === 409) {
const now = response.body; // who saved it, when, and what it holds now
throw new ConflictError({ version: { token: now.etag, by: now.changedBy, at: now.changedAt }, theirs: now.values });
}
return { id: response.body.id, version: { token: response.body.etag } };
},
};
The form then says it over the record — Mona changed this record at 10:42, the fields she changed and those you both changed, in the page's language and its way of writing a time — and offers two answers. Nothing of the person's is lost while they choose:
- Reload shows the record as the other person left it, and lists the person's own changes beside it, each with Put back (
form.reloadTheirs(),state.setAside,form.putBack(field)). - Keep mine saves the person's changes over the record as it is now: the other person's values stay wherever this one changed nothing (
form.keepMine()). It saves with the version the conflict named, so a source needs no second way to save; a source that saves whole records getsvaluesas theirs with these changes over them — read again first when the conflict did not carry the record. If it cannot be read, nothing is saved over work the person never saw: the form says so (conflict.unread), and they may try again or Reload. If a third person saved in between, that is another conflict.
Save pressed again while a save is on its way — Ctrl+Enter twice — waits for it, and saves with the version it got back: never a conflict with yourself. After Reload, the changes set aside count as unsaved until they are put back or let go — the list's × asks before it lets them go. A change made while a save is on its way stays a change to save, and the status says Saved, but not all your changes. Every way a form's values go passes one check inside the form, form.leave(): another record (the pager, an action's answer naming one, Duplicate's copy), the record loaded again (a reload step, an answer's reload: true), a reset step, and your host's close, which the form takes once where it is made. It first waits for a save on its way and files on theirs, the page saying what it waits for, so a save's answer never lands on another record; then it looks at the record as it is now. It asks "Discard your changes?", the focus on Cancel so Enter keeps the person where they are, only when their work is at risk: a change of theirs the last save did not send — typed while it was on its way, while the run that saved went on, or since; a value your page's steps, rules or app set is never theirs — a file not saved yet, changes set aside. A dialog, a panel and a page opened in place hold what was typed in them and nothing else saves it: their Escape, × and Back ask about every change not saved, before the record's first save too (since 0.26: a related list's New or row and a calendar's New closed unasked before). Once a save in a dialog, a panel or a page in place went through, it comes back saved however it is closed. Call form.leave() before your app's own ways out; unsavedWork(form.getState()) answers for a browser's beforeunload. The question comes through your host's ask(message, { discard: true }).
A new record, and a source that tells no version, are never checked. saveProblemOf(error) reads a ConflictError as { kind: "conflict", conflict } without instanceof, so an app with two copies of core still shows it. Try it in the two tabs demo.
Live records: changes pushed, and who else is here
Your app's socket — server-sent events, a database's listener — tells an open record what others do to it, through two members. subscribe(record, push) is asked as a record is shown and stopped as another is: push { type: 'record', version, values, by, at } as someone else saves it. Where the person has changed nothing, their values are laid on the record at once — no change to save — and said: Mona Adel changed Price. After a change of theirs, it waits as the conflict a save would meet, the banner above saying who changed what, with Reload and Keep mine; their typing is never touched. A change without its values is read (load); one whose version is this form's own save is let go. { type: 'deleted' } is said.
presence(request, push) is asked with this person (user) and whether they are changing the record (editing), and asked again as that turns: push the others with it open, each { id, name, editing? }. Over the record: their initials, a ring round whoever is editing, and Also here: Mona Adel (editing).
const source: DataSource = {
...rest,
subscribe: ({ model, id }, push) => socket.on(`${model}/${id}`, (change) => push({ type: 'record', ...change })),
presence: ({ model, id, user, editing }, push) => socket.join(`${model}/${id}`, { user, editing }, (people) => push(people)),
};
@fieldia/chatter's source has subscribe(record, push) too, pushing { type: 'message' } and { type: 'delivery' }: the same call with types that never meet, so one function of yours on one socket may serve both — each takes only its own type. The memory source does both with live: true: changeElsewhere pushes, arrive and leave bring others in and out. It all comes in a part of its own, fieldia.live.js, asked for only where your source has either member. Without live the memory source has none of the four, as a source without a socket; its template members likewise come with its templates option ({} for none yet).
Record templates
A page with "templates": true has a Templates menu over its record: Save as template… keeps what the record holds by a name — "Botox package", "Standard lease" — and a new record starts from one, its values written as the person's own changes (Ctrl+Z takes each back). Kept: every field a person fills in — never the record's name, a file, a value worked out or locked — or the page's templates.fields alone; a table's lines without their ids. A name already kept is asked about first — "Replace “Botox package”?", answered Replace or Cancel, Cancel asking the name again. Through your source's templates, saveTemplate and deleteTemplate, shared as you share them; without them, in the viewer's preferences: the person's own.
What this person may do with a record
The same loadedRecord tells what the person may do with the record, as can. Everything is allowed unless it says false, so a source that says nothing keeps today's behaviour. The form keeps to it before any source is asked — and the source should still refuse on its side:
return loadedRecord(row.values, {
version: { token: row.etag },
can: {
edit: row.isMine, // false: every field read-only, no Save, no Edit
delete: false, // false: Delete and the buttons whose steps delete are hidden
archive: true, duplicate: true, // the same for Archive and Unarchive, and for Duplicate
readonlyFields: ['commission'], // locked, with a lock that says why
hiddenFields: ['margin'], // not shown, never asked for, left out of what a save sends
reason: 'Only Mona, the lead’s agent, can change it.',
},
});
What is not allowed is hidden, never shown greyed out, and the reason is said: over the record when it is only to be read, by a locked field's lock, and at the foot of the gear menu for an action it leaves out — the source's reason, or Fieldia's own words in the page's language. A save can change it (a stage that locks the record): return can with the SaveResult. Each row of a list may carry can and version too. See it as a viewer who may only read.
Many records at once: every match, export and bulk edit
A list's Select all 1,284 that match, its Export and its Edit (see lists) read three optional members. Without them each still works: the list reads list a page at a time, writes the file in the browser, and saves each record in turn.
// Every matching id, in the list's order, beside one page (limit 0 for the ids alone).
list({ model, fields, filter, sort, offset, limit, allIds: true }): Promise<{ records, total, allIds?: RecordId[] }>;
// One value in a field of each record. Refuse a record as its save would be refused:
// one this person may not change, or one changed since the version it was listed at.
writeMany?({ model, ids, values: { state: 'customer' }, fields, versions?: { [id]: RecordVersion } }):
Promise<{ failed: { id, message, problem?: SaveProblem }[] }>;
// A list's export written on the server.
exportRecords?({ model, format: 'xlsx' | 'csv', columns: [{ field, label }], ids?, filter, sort, count, name, locale }):
Promise<{ name, data?: Blob | ArrayBuffer | string, type?, url? } | { message: string } | false>;
allIdsshorter thantotalmeans you stopped early: the list says 1,000 of 1,284 could be selected rather than claim all. Each row'sversionandcanare what an Edit sends and keeps to.writeManyis asked a thousand ids at a time. Every id not infailedis taken as changed; a failure'smessageis said beside the record's name, and itsproblem(aConflictError's, say) lets the list name who changed it. A call that throws counts each of its records as not changed, with its words. WithoutwriteMany, each record is asavewithpartial: true:valuesandchangeshold the one field.exportRecordsgets the list's columns and words, the tickedids(none: every recordfilterfinds), the order and the file's name. Answer with the file and the browser saves it; with{ message }— it will be emailed to you — and the list says it; or withfalseto let the browser write this one after all, as for a small export.
A list changed in place
A list whose cells are changed in place (editable, see lists) asks nothing new of your source. Each row is a record's own form, its values as the list read them — no load for what the list shows already — and it is saved as the person leaves it:
// A row left: the fields the person changed alone, with the version it was listed at.
save({ model, id, fields, changes, values, partial: true, version }) // values and fields: the changed ones alone
// A row added at the end: a new record, whole.
save({ model, id: null, fields, changes, values })
// Rows given the same change at once (one value pasted down a column): one call, each with its version.
writeMany?({ model, ids, values, fields, versions })
// A conflict's Reload, Keep mine reading theirs: the row as you have it now (else list, by its id).
load?({ model, id, fields })
- Versions. Each row's
version(ListedRecord.version) goes with its save; one changed since is refused withConflictErrorand said under the row as a record's page says it, with Reload and Keep mine. A source that tells no versions is not checked. - Permissions. A row whose
can.editis false is not opened for typing, nor a cell ofcan.readonlyFieldsorcan.hiddenFields; yoursavestill refuses as it would. - Refused.
saveRefused({ kind, message })— a rule of yours, a field's own words — is said under the row, the person's typing kept for them to put right or put back. - Worked out. What a worked-out column reads is asked for with the list's fields, and worked out as the cells are typed; the values your save answers with replace them.
- A row's links, choices and files ask
search,create,options,onchangeanduploadas a form does. Withoutsave, the list is read and opened as ever.
Many records made at once: a list's Import
A list's Import (see lists) checks every row in the browser first, then writes those that pass. Two optional members make it faster and bigger; without them it still works, a save of each row as a new record, and its Undo uses delete.
// Many records, each with its own values, a few hundred at a time. Answer each in order:
// the id it was made with, or why it was not (and the problem, as a save would throw it).
createMany?({ model, records: Values[], fields }):
Promise<{ records: ({ id: RecordId } | { message: string; problem?: SaveProblem })[] }>;
// A list's import taken on the server, asked once the person has matched the columns.
importRecords?({ model, file, columns: [{ header, field | null }], rows, fields, locale, dateOrder }):
Promise<{ message: string } | false>;
createManyis asked five hundred records at a time, each its row's values and the page's defaults, links as{ id, label }. A record left unanswered is taken as not made. Without it, each row issave(newRecordSave(model, fields, values)):id: null, every value, a many2many's links as oneset. Refuse a record as its save would be refused; the list names it by its row in the file.importRecordsgets the file as picked (a browser'sFile), its columns and the field each goes into, how many rows it holds, and the page's language and date order. Answer{ message }— your file is being imported: you will get an email — and the list says it; orfalseto let the browser import this one after all. The browser reads at most 50,000 rows: a bigger file is imported only where your source takes it.
An adapter for a REST API
import type { DataSource } from '@fieldia/core';
export const api: DataSource = {
async load({ model, id }) {
return (await fetch(`/api/${model}/${id}`)).json();
},
async save({ model, id, values }) {
const response = await fetch(id === null ? `/api/${model}` : `/api/${model}/${id}`, {
method: id === null ? 'POST' : 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(values),
});
const saved = await response.json();
return { id: saved.id, values: saved };
},
async search({ model, query, limit = 8 }) {
const rows = await (await fetch(`/api/${model}?q=${encodeURIComponent(query)}&limit=${limit}`)).json();
return rows.map((row: { id: number; name: string }) => ({ id: row.id, label: row.name }));
},
async submit({ pageId, values }) {
const response = await fetch(`/api/responses/${pageId}`, { method: 'POST', body: JSON.stringify(values) });
// The reference it was given, which the page's ending says: "Your booking is {id}".
const kept = await response.json();
return { id: kept.reference, values: { confirmed_at: kept.confirmed_at } };
},
};
The memory data source
createMemoryDataSource() implements every method in memory. It is what the demos and tests use, and a good way to try a page before a backend exists. You can seed it with records, search labels and onchange rules:
import { createMemoryDataSource } from '@fieldia/core';
const dataSource = createMemoryDataSource({
records: { partner: { 1: { name: 'Nile Towers', is_company: true } }, country: { 63: { name: 'Egypt' } } },
onchange: { partner: { is_company: (values) => ({ title: values.is_company ? null : values.title }) } },
warnings: { partner: { credit_limit: (values) => (values.credit_limit > 100000 ? 'Above the approval limit' : null) } },
delayMs: 300, // answer slowly, to see loading states
versions: { by: 'Sara' }, // a version for each record; a save over a newer one is a conflict
can: { lead: (values) => (values.stage === 'won' ? { edit: false, reason: 'A won lead is closed.' } : undefined) },
});
dataSource.responses; // every submitted response, for tests
// Each response answered as your server would: createMemoryDataSource({ submitted: (request, count) => ({ id: `B-${1042 + count}` }) })
dataSource.changeElsewhere('lead', 1, { stage: 'visit' }, { by: 'Mona' }); // as someone else, on another screen
Its limits counts the responses it takes — and those answeredElsewhere(pageId, values) says someone else sent meanwhile, never this person's — over the starting counts its limits option gives by page ({ 'event-signup': { responses: 147, perChoice: { session: { morning: 28 } } } }), and a record page's model's records but the one edited. Its saveDraft keys drafts draft-1, draft-2…, kept in dataSource.drafts (each with its page and later), answering Continue later with draftLink(key)'s link where given; loadDraft finds them, and those its drafts option starts with. A send lets its draft go.
Its approvals and decide work as a small approval engine, from its approvals option by model: { 'purchase.order': (values) => ({ levels: [{ id: 'finance', name: 'Finance', approvers: [{ id: 21, name: 'Mona Adel' }] }], asked: values.state === 'to_approve', approved: { state: 'purchase' }, rejected: { state: 'rejected' } }) } — the levels a record must pass (or null: none), in turn unless together, whether it is sent for approval now (asked), and what it holds once approved or rejected. It keeps each decision, starts a round each time a record is sent again, and finds the person deciding by the form's user; approvalHistory (by 'model:id') is what it starts from.
A text kept in several languages ({ ar, en }) is found by a search in any of them, and read in its language option's — the reader's, createMemoryDataSource({ language: 'ar' }) — where it says one text: a link's name, a list's order; the first typed where it has none there, or the option is left out.
Given views — by page id, {} for none yet — it keeps lists' saved views as a server does: the team's shared ones it starts with (each with who made it, by) and the person's own (mine), and those saved, the person's own, view-1, view-2…; one default of a kind (the person's own, or the team's), another's view refused. Without the option it has none of the three, and a list keeps its favourites in the browser.
Its groups and totals group a date by the span it falls in (interval), and total an amount in one currency only where currencies names the field holding each record's (see lists that add up).
Its slots answers from booking schedules, with scheduleSlots: the hours each day of the week on a zone's clock, a booking's length and the minutes kept free after one, holidays, and the records its bookings are — each car's own, with same — a time the clocks skip that day left out, and times gone by too:
import { createMemoryDataSource, scheduleSlots } from '@fieldia/core';
const weekday = [['09:00', '13:00'], ['14:00', '18:00']];
const dataSource = createMemoryDataSource({
records,
slots: scheduleSlots({
showroom: {
timeZone: 'Europe/Berlin',
hours: { 1: weekday, 2: weekday, 3: weekday, 4: weekday, 5: weekday, 6: [['10:00', '14:00']] }, // 1 Monday … 7 Sunday
length: 45, // minutes a drive lasts
between: 15, // minutes kept free after each
holidays: { '2026-12-25': 'Christmas Day' },
bookings: { model: 'drive.booking', field: 'start', endField: 'stop', same: ['car'] },
},
}),
});
Its duplicates answers with alikeRecords(): each record of the model holding the same value in a field asked as people write them apart — a phone's spaces and dashes, an email in any case, a link by its record — or, in its name field, a name close enough. Its merge keeps one record with the values picked, takes the others away, and moves the links to them to it; its notDuplicates and markNotDuplicate keep what was let be as pairs (notDuplicatePairs, by model, read from either side), starting from the option of that name:
import { alikeRecords, createMemoryDataSource } from '@fieldia/core';
const dataSource = createMemoryDataSource({ records, duplicates: alikeRecords() });
Its AI help — suggest, rewrite and searchToFilter — is there only where its assist option answers it. assistStandIn() is a stand-in for demos and tests, with no model and no keys: words read by their patterns (a signature's name, job, company, e-mail, phones, website and address; a search's choices, links and numbers — “villas in New Cairo under 15M”), a polish that puts capitals and full stops in and writes out “u”, “pls” and “asap”, a draft from a template of yours. Each of its answers says so: “Stand-in AI, no model: …”.
import { assistStandIn, createMemoryDataSource } from '@fieldia/core';
const dataSource = createMemoryDataSource({ records, assist: assistStandIn({ drafts: { 'enquiry.reply': (values) => `Dear ${values.partner_name}, …` } }) });
Its list gives allIds when asked, and its writeMany refuses each record as its save would (the person's can, a version older than the record's); its createMany makes each record as its save makes a new one; it has no exportRecords or importRecords, so the browser writes an export and reads an import, as without a server. Its upload keeps each file as a data: address, so a preview needs nothing else. storage makes it as slow, or as unreliable, as a real store, to see files on their way and Retry:
const dataSource = createMemoryDataSource({
storage: {
bytesPerSecond: 150_000, // a phone sending on mobile data
fails: (file, attempt) => file.name === 'balcony.jpg' && attempt === 1, // fails once, partway: Retry mends it
// or words, for the store refusing the file: (file) => file.size > 5e6 && 'Photos up to 5 MB'
},
});