LuxelEspañol

Luxel v0.2 · Guide · part 2 of 2

Collections (2)

Server-side pagination

The pager is a second collection. Each item is a page; its key is the page id the server will read back, and its action sends that key as param:

‹Collection bind="contacts.pages" itemKey="id" maxItems={10} label="Pages" className="pager"> {(p) => ( ‹Action event="contacts.page" param={p.id} status="result" className="pager__page"> {p.label} ‹/Action> )} ‹/Collection>

// contract pages: collection({ key: 'id', fields: { label: text() } }), // ... events: { // A page key ("p2") names no record: LOCAL. 'contacts.page': allow(['user'], { effect: 'read', refs: { param: LOCAL } }), },

// handler export const contactsPage = defineEvent(events.contactsPage, async (_input, ctx) => { const page = Number(/^p(\d{1,2})$/.exec(ctx.param)?.[1] ?? 0); const p = contactPage(ctx as Ctx, Math.max(1, page)); if (page < 1 || page > p.pages) return ctx.reject('NOT_FOUND', 'Page not available.'); return ctx .set('contacts.rows', p.rows) .set('contacts.pages', p.pager) .set('contacts.summary', p.summary as never) .version(p.version); });

(This is the paging handler of an app with a hand-written contract; contactPage and Ctx are helpers of its server/events.ts. The create-luxel template writes the same handler in a screen file: page: s.event({ policy: allow(USER, { effect: 'read' }), param: local() }, …), see Screens.)

  • The page count, the summary ("6 contacts · page 2 of 2") and the pager items are all computed by the server. The browser never adds one to a page number.
  • ctx.param is untrusted input: parse it strictly and refuse anything else.
  • A page change is a read (effect: 'read'): nothing is stored, and no idempotency key is claimed.

Search

A search is a field, an action that sends it, and a handler that reads the matching page:

‹Row className="sheet__search"> ‹Field name="q" label="Search" maxLength={40} autoComplete="off" placeholder="Code, name or city" /> ‹Action id="search" event="agencies.search" fields={['q']} status="result" className="button button--ghost"> Search ‹/Action> ‹/Row>

To keep the search when the person changes page, the pager's actions send the field too:

‹Collection bind="agencies.pages" itemKey="id" maxItems={12} label="Pages" className="pager"> {(p) => ( ‹Action event="agencies.page" param={p.id} fields={['q']} status="result" className="pager__page"> {p.label} ‹/Action> )} ‹/Collection>

The handler of agencies.page receives { q } and ctx.param. Filtering, counting and sorting run on the server (in the lab, in one PostgreSQL statement per answer).

Row actions and object authorization

A row action sends the item key as param. Any id an event carries must name its resource kind in refs (LUXEL-E045), and the app must give a scope function for that kind:

// contract 'contact.remove': allow(['user'], { refs: { param: 'contact' } }),

// server/bindings.mjs export const scopes = { // The ids among `ids` that belong to this session's user. contact: async (_tx, session, ids) => contactOps.owned(session.userId, ids), };

// handler: ctx.param is one of this user's contacts; the scope function checked it first. export const contactRemove = defineEvent(events.contactRemove, async (_input, ctx) => { contactOps.remove(ctx.session.userId as string, ctx.param); // ...read the page again into `p` return ctx.set('contacts.rows', p.rows).success('removed').version(p.version); });

Before the handler runs, the framework calls the scope function with every id the event carries, inside the event's transaction. An id not returned refuses the event with the generic VALIDATION answer: an id of another user is answered exactly like an id that does not exist. The page learns nothing about other scopes. A host whose contract names a kind without a scope function does not start.

See Server for the details.

Rows with inputs

A collection whose rows contain Fields and Selects is a form with lines: an order, a delivery guide. Each input of a row is a value() field of the item, named like the input:

// contract guide: { state: { guide: { products: options({ max: 30 }), lines: collection({ key: 'id', fields: { product: value(), qty: value(), amount: money() } }), total: money(), }, }, events: { 'guide.line-change': allow(OPERATOR, { effect: 'read', refs: { param: LOCAL, 'lines.product': 'product' } }), 'guide.line-add': allow(OPERATOR, { effect: 'read', refs: { 'lines.product': 'product' } }), 'guide.submit': allow(OPERATOR, { refs: { agency: 'agency', 'lines.product': 'product' } }), }, },

‹Collection bind="guide.lines" itemKey="id" maxItems={50} as="tbody" label="Lines" changeEvent="guide.line-change" changeStatus="result"> {(line) => ( ‹Stack as="tr"> ‹Stack as="td">‹Select name="product" label="Product" options="guide.products" />‹/Stack> ‹Stack as="td">‹Field name="qty" label="Quantity" type="integer" min={1} max={9999} maxLength={4} />‹/Stack> ‹Text as="td" className="table__amount">{line.amount}‹/Text> ‹/Stack> )} ‹/Collection> ‹Action id="add" event="guide.line-add" fields={['lines']} status="result">Add line‹/Action> ‹Text bind="guide.total" label="Total" />

  • changeEvent is sent when a field of a row is left or a select changes, never per keystroke. It carries the rows of the collection and the key of the row that changed (ctx.param).
  • The rows as an input. Any action can send the rows with fields={['‹collection id>']} (the id is the last segment of bind, here lines). The handler gets them typed: ReadonlyArray<{ key: string; product: string; qty: string }>.
  • Ids inside rows. A select column carries ids: name its kind in refs as '‹rows>.‹column>', here 'lines.product': 'product'. Every row's value is re-checked by the scope function.
  • Row select options are fixed for the page. They come from the third argument of ctx.snapshot (the "fill"), and answers do not change them:

export const guideLoad = defineLoad(views.guide, async (ctx) => { const products = await productOps.list(ctx.tx as Db); return ctx.snapshot( 0, // a new form shows no versioned resource { 'guide.lines': [{ id: 'l1', product: '', qty: '', amount: 0 }], 'guide.total': 0 }, { 'guide.products': products.map((p) => ({ key: p.id, label: p.name })) }, ); });

  • Every recalculation is a round trip. The line amount and the total come back from the server:

export const guideLineChange = defineEvent(events.guideLineChange, async ({ lines }, ctx) => { const { amounts, total } = await guideOps.price(ctx.tx as Db, lines); return ctx.item('guide.lines', ctx.param, { amount: amounts.get(ctx.param) ?? 0 }).set('guide.total', total); });

  • policies.maxRows bounds a row collection with inputs (LUXEL-E046).

Changing a list from a handler

CallEffect
ctx.set(path, items)Replaces the whole list
ctx.item(path, key, fields)Changes one item: only the fields given
ctx.insert(path, key, fields, after)Adds an item right after the item after ('' = first)
ctx.remove(path, key)Removes one item
ctx.move(path, key, after)Moves one item right after after ('' = first)
ctx.sync(path, before, now, seen)Brings a versioned list from what the page showed to what it is now (below)

return ctx .insert('guide.lines', key, { product: '', qty: '', amount: 0 }, lines.at(-1)?.key ?? '') .set('guide.total', total);

In a row, fields are written by kind: texts (text, money, date, quantity), input values, numbers and states. When a handler changes one field of a kind, it must give every field of that kind for that item, or the server throws. ctx.set on a list needs every field of every item. In the example above, amount is the row's only text field, so ctx.item(..., { amount }) is complete.

Versioned lists: ctx.sync

A list that other people change (annulments, corrections, new rows) can drift from what a page showed. ctx.sync brings it back exactly, whatever version the page holds:

ctx.sync('corrections.rows', before, now, ctx.seen)

  • before: the keys, in order, that the page showed at its version ctx.seen. The server computes them (for example, rows created up to that version and not annulled by then).
  • now: the list as it is now, each item as { key, version, fields }, where version is the row's version.
  • A key gone is removed; a key kept whose version is above seen is replaced whole (a correction); a new key is inserted where it goes; a key whose place changed is moved.

export const movementVoid = defineEvent( events.movementVoid, async (_input, ctx) => { const userId = ctx.session.userId as string; const done = await ledgerOps.void(ctx.tx as Db, userId, ctx.param); if (!done) return ctx.reject('VALIDATION', 'The movement is no longer available.'); // What the page showed at its version → what is there now (this annulment and anything else). const l = await ledgerOps.latest(ctx.tx as Db, userId, { seen: ctx.seen }); return ctx .sync('corrections.rows', l.before, l.rows.map((m) => ({ key: m.id, version: m.version, fields: correctionItem(m) })), ctx.seen) .version(l.version); }, { lock: (ctx) => ledgerOps.lock(ctx.tx as Db, ctx.session.userId as string, ctx.param as string), compare: 'not-newer' }, );

ledgerOps, correctionItem and Db are the lab's own (examples/03-luxel/server/events.ts).

The browser applies remove, item, insert and move operations and computes nothing. For before to be exact, one scope's writes must commit in version order; the lab takes a per-user transaction lock before each write (ADR-043). See Server for lock and compare.

Edit this page on GitHub

This page: 7.9 KB of JavaScript (Luxel's shared runtime), 0 KB from your app.

Measured when the site is built: the runtime files this page loads, compressed as they are sent.

Made by IntiOps. The Luxel 0.1.0 betas are on npm (0.1.0-beta.1, 0.1.0-beta.2), with an alpha of 0.2 (0.2.0-alpha.1): no external security review yet.