Mixins / foldkit-mixins

SlotView

SlotView.define(slots, render) is a pure view that publishes slots. Attach with SlotView.attach, Style.attach or Behavior.attach; each returns a new view.

Nothing but the render callback's builder names the view's Message universe, so plain define infers it from an explicit h: HtmlBuilder<Message> annotation. Without one, Message becomes unknown and the eventual variance error is hard to read. SlotView.forMessages<Message>().define(slots, render) fixes the universe up front instead; Input still comes from the callback's own input annotation.

Behavior.attach uses the behavior's Input as the attached view's Input, so declare a behavior over the view's input type, not merely the subset of fields it happens to read.

Naming the slots, input and Messages once: SlotView.over

A Behavior is made before the view it meets, so Behavior.forSlots(S)<Input, Message> names both types again for every Behavior. SlotView.over(S)<Input, Message>() names them once and hands back define, behavior and parts with all three fixed, so nothing passed to them is annotated:

ts
const Fields = SlotView.over(FieldSlots)<FieldInput, Message>()

const Validates = Fields.behavior(
  { input: { attributes: ({ input, h }) => [h.AriaInvalid(input.invalid)] } },
  { name: 'Validates' },
)
const BoundField = Fields.define((input, slots, h) =>
  h.label(slots.root.attrs(), [
    h.input(
      slots.input.attrs([
        h.Value(input.value),
        h.OnInput(value => Message.ChangedValue({ value })),
      ]),
    ),
  ]),
).pipe(Behavior.attach(Validates))

Fields.define is SlotView.define, Fields.behavior is Behavior.forSlots and Fields.parts is SlotView.parts: the binder makes no new kind of value and holds no state. A Behavior from a binder over another Message universe is still refused at Behavior.attach. foldkit-mixins-surface's SurfaceView.over(surface, slots) is the same binder with both types read from the Surface. A factory that takes slots can take a binder in their place, telling the two apart with SlotView.isBound.

What a view remembers of its attachments

Each attachment keeps its name, and a Style or Behavior also its meta: its kind and, per slot, what it requires, what it supplies (its provides, see Obligations) and whether it reads the input. A Mixin made with Mixin.make or Mixin.dynamic carries none; Mixin.compose records its parts in order. A name addresses an attachment:

ts
const Unchecked = BoundField.pipe(SlotView.detach('Validates'))
const Checked = Unchecked.pipe(Behavior.attach(Validates))
const Swapped = Checked.pipe(SlotView.replace('Validates', Validates.mixin))

detach and replace return a new view, replace keeping the attachment's place in the resolution order. Each throws mixins:unknown-attachment for a name the view does not hold and mixins:ambiguous-attachment for one it holds twice, so name a Behavior you mean to address (an unnamed one is called Behavior).

Describing a view, and what one input resolves to

SlotView.describe(view) is the view as data: its slots, and each attachment in order with, per slot, what it requires, what it supplies and the classes and Mounts it contributes. It needs no input and calls no contribution; one that is a function of the input reads 'unknown'. It reads the view value, so a view you attach to or detach from has a description of its own and the first one's does not change. A JSON.parse(JSON.stringify(description)) equals it, and SlotView.toMarkdown(description) prints it.

ts
const description = SlotView.describe(Checked)
// description.attachments[0]: { order, name, kind, slots: { input: { requires, provides, contributes } } }
const markdown = SlotView.toMarkdown(description)

SlotView.resolution(view, input) evaluates every contribution for one input and reports, per slot, the class tokens, style property names, attribute names, event names and Mount names, each with the attachment that gave it. It reports no attribute value, style value or Mount args, since any of them may be the input's (a password in Value); class tokens are reported as given, so a class built from input text surfaces it. It builds handlers with the inert builder and calls none, runs no Mount, and returns a conflict as a finding where resolve would throw. It does not draw the view, so a clash with the view's own base attributes is not reported. Attribute and event names are as the resolver compares them (lower case, no hyphens).

findings also warn (severity: 'warning') of an unnamed attachment and of two with one name, which detach and replace cannot address.

For per-item groups such as tabs, options or calendar cells, use SlotView.buildersFor(slots, mixins, { input, h }) and map the items yourself. One contribution then applies to every item while each item's base attributes retain their own event ownership.

Parts: redraw only what changed

A SlotView runs whole on every change to its input. A larger view can be cut into parts, each declaring the input keys it reads and given only those. A part runs again only when one of those values changed by identity; otherwise Foldkit reuses its last drawing without diffing it.

ts
type Input = { readonly title: string; readonly count: number }
const Parts = SlotView.parts(PanelSlots)<Input, Message>()

const Title = Parts.part('Title', { reads: ['title'] }, (input, slots, h) =>
  h.h2(slots.title.attrs(), [input.title]),
)
const Count = Parts.part('Count', { reads: ['count'] }, (input, slots, h) =>
  h.p(slots.count.attrs(), [String(input.count)]),
)
const Panel = Parts.assemble((input, slots, h, draw) =>
  h.section(slots.root.attrs(), [draw(Title), draw(Count)]),
)

input.count inside Title does not compile, so a part cannot read a value it is not redrawn for. Panel is an ordinary SlotView: Styles and Behaviors attach to it and reach every part's Slots.

  • A part's own Behaviors go in its behaviors option, declared over the part's selection (Pick<Input, 'count'>), and are resolved against it. A part is found only by drawing it, so A11y.conform reads none of its Behaviors' obligations, at the type level or at run time: attach a Behavior that must count to the assembly, and the finding says so when it is put on a part.
  • A Mixin attached to the whole view that reads the input (a Behavior's attributes, Style.whenInput) is resolved against the whole input, so the parts it reaches are drawn again on every change: correct, not cached. Static Styles cost nothing.
  • Memoizing needs a running application. Drawn inert (a test, a server's first pass), every part is drawn afresh.

A Slot drawn once per item can memoize each item, in a part or any SlotView:

ts
const drawRow = (
  slots: SlotView.SlotBuilders<typeof ListSlots, Message>,
  h: HtmlBuilder<Message>,
  { index, text }: { readonly index: number; readonly text: string },
) => h.li(slots.row.attrs([h.Key(text)], { index, id: text }), [text])

const Rows = ListParts.part('Rows', { reads: ['rows'] }, (input, slots, h) =>
  h.ul(
    slots.root.attrs(),
    input.rows.map((text, index) => slots.row.lazy({ index, id: text }, drawRow, { index, text })),
  ),
)

An item is drawn again only when one of its arguments changed by identity, or when a Mixin gave the Slots it used something different for it (a static Style by identity, so two views apart only by a Style draw their rows apart). A Behavior that works out a roving tab stop from the whole list redraws the row the stop left and the row it reached, and no other. drawRow reads only its arguments, so define it once, not per render. A Mixin that gives an item a handler made per render, and an item drawing that holds another, are drawn every time: correct, not cached. An item no longer drawn is forgotten: a key is drawn once per pass, so a key drawn again starts a new pass, and what neither that pass nor the one before drew is dropped. Keys may come from something that keeps changing (a search's results, 100,000 rows scrolled through) without the memo growing with them. The memo is one per drawing function: two views drawing the same key with one drawRow share it, and each misses whenever what it gives the row differs from the other's. Drawn inert, nothing is kept.

Regions: redraw by the Model paths read

A part reads keys of its view's input. An application view's input is the whole Model, and the values a piece of it needs sit at paths below its fields: a region names them through the application's field references, and is drawn again only when a value at one of those paths changed.

ts
const Header = SlotView.region(
  Projection.struct({ cart: App.model.cart, title: App.model.page.title }),
  ({ cart, title }, slots: SlotView.SlotBuilders<typeof PageSlots, Message>, h: HtmlBuilder<Message>) =>
    h.header(slots.header.attrs(), [title, ` (${cart.length} in the cart)`]),
)
// In the page's render, beside anything else it draws:
Header(model, slots, h)

Projection and App.model are foldkit-surface's (any value with dependencies and read will do). Each render, the region compares the values at its paths with the last ones, by identity: all the same, it neither reads nor draws, and Foldkit reuses its last drawing without diffing it. One changed, it reads; a read holding the same fields as the last (a value derived with Projection.fromReader that came out the same) is not drawn either. That is Projection.derive's rule, which the region is built on: a value a view works out on every render without drawing it (a filtered list, a summary of many Remote reads) is a Projection.derive, and a region can be drawn from one. A Remote read declares no Model path, alone or in a Projection.struct beside fields, so a region over one reads on every render and is drawn again when the read gives new fields. Drawn from a Projection.derive that names the store's field (App.model.remote) and makes the Remote read inside, it is not read while the store holds.

  • It reads only its value. Header's drawing is given what the Projection reads, so it cannot read a path it is not drawn again for. A helper written over the Model takes Pick<Model, …> instead.
  • Its paths must be from the root. A Projection built from field references has them; one from Projection.fromReader needs its dependencies, and one with none is read on every render.
  • Slots, Mixins and nesting work as for an item: a Mixin reading the view's input draws it every time, and a region or item drawn inside another is drawn in place, the outer one every time. Put regions where their reads are narrow (a header, a toolbar, a panel), and items in the lists between them.
  • A reused drawing is not patched. While its paths hold, Foldkit does not touch the region's DOM, so a field whose update refused a keystroke shows what was typed until a path it reads changes. Keep such a field's value among its reads, or outside a region.
  • Memoizing needs a running application, as for parts.

With foldkit-surface

Mixins do not require Surface, but the two fit naturally: Surface says what a feature may observe and emit; slots say where that feature may be customized.

foldkit-mixins-surface renders a Surface projection through a SlotView, so a Behavior reads the projected input rather than the root application Model, and its builder carries the Surface's Message subset.

Application Model / Message
          │
       Surface
  what may be seen/emitted
          │
       SlotView
  where it may be customized
          │
   Style + Behavior