qat

Components: children, slots, compound components

Children and slots: placement

A component receives what is written between its tags as children, a function it renders where it wants. Elements with slot="name" go to slots.name instead (slots is one prop, an object of them; one that was not given is undefined, so slots?.footer ?? … is its fallback):

.qx10 linesOpen in the playground
// card.qx
export default function Card({ children, slots }) {
  return (
    <article class="card">
      <header>{slots?.header}</header>
      {children}
      <footer>{slots?.footer}</footer>
    </article>
  )
}
.qx12 linesOpen in the playground
// usage.qx
import Card from './card.qx'

export default function Usage() {
  return (
    <Card>
      <h2 slot="header">Title</h2>
      <p>Body</p>
      <small slot="footer">Footer</small>
    </Card>
  )
}

Slots are about placement: the parent decides where each piece of content goes, and the pieces know nothing about each other.

Compound components: shared behavior

When the parts must behave together — a selection, keyboard navigation between them, ARIA relationships (aria-controls, aria-labelledby, roving tabindex) — make them parts of one component. The parent provides a context; each part injects it; parts that need to be known (for keyboard order) register while they are mounted:

.qx30 lines, 3 reactive namesOpen in the playground
// tabs.qx (shortened: examples/shop/src/components/tabs.qx is the full one)
const TabsContext = Symbol('tabs')

export default function Tabs({ value, children }) {
  let emit = emits<{ 'update:value': string }>()
  let own = state<string | undefined>(undefined)
  let tabs = shallow<string[]>([])
  let selected = derived(value ?? own ?? tabs[0])
  provide(TabsContext, {
    selected: () => selected,
    select: (id: string) => ((own = id), emit('update:value', id)),
    // mount's cleanup unregisters: the order is the tabs actually on the page
    register: (id: string) => ((tabs = [...tabs, id]), () => (tabs = tabs.filter((t) => t !== id))),
  })
  return <div class="tabs">{children}</div>
}

function Tab({ id, children }) {
  const ctx = inject(TabsContext)
  mount(() => ctx.register(id))
  return <button role="tab" aria-selected={String(ctx.selected() === id)} on:click={() => ctx.select(id)}>{children}</button>
}

function Panel({ id, children }) {
  const ctx = inject(TabsContext)
  return <div role="tabpanel" hidden={ctx.selected() !== id}>{children}</div>
}

Tabs.Tab = Tab
Tabs.Panel = Panel
own statetabs stateselected derived
.qx14 lines, 1 reactive nameOpen in the playground
// product.qx
import Tabs from './tabs.qx'

export default function Product() {
  let tab = state('about')
  return (
    <Tabs bind:value={tab}>
      <Tabs.Tab id="about">About</Tabs.Tab>
      <Tabs.Tab id="reviews">Reviews</Tabs.Tab>
      <Tabs.Panel id="about">…</Tabs.Panel>
      <Tabs.Panel id="reviews">…</Tabs.Panel>
    </Tabs>
  )
}
tab state
  • <Tabs.Tab> is an ordinary component reference (a member expression), in .qx and .tsx.
  • Tabs.Tab = Tab types the part: qatjs check checks <Tabs.Tab>'s props and the editor goes to its definition.
  • Controlled or uncontrolled: with bind:value the parent owns the selection (value is set, update:value reports changes); without it the component keeps its own.

Rule of thumb: slots when the parent arranges independent content; compound components when the parts share state and behavior.

Components of other frameworks: Vue, Angular, React

A component from a Vue, Angular or React package is used as a tag, like a Qat component. The compiler sees whose it is: a package whose package.json has vue, @angular/core or react as a peer or a dependency, or a local file that declares an Angular component (@Component). It wraps the import with that framework's bridge. The component then renders with the app's own copy of its framework, inside the Qat tree:

.qx15 lines, 2 reactive namesOpen in the playground
import { VueDatePicker } from '@vuepic/vue-datepicker'
import { OrdersTable } from './orders-table.component.ts'

export default function Booking() {
  let day = state(null)
  let picked = state('')
  return (
    <main>
      <VueDatePicker bind:modelValue={day} placeholder="Pick a day" aria-label="Booking day" on:closed={() => (picked = '')} />
      <OrdersTable rows={[]} picked={picked} on:select={(o) => (picked = o.id)} role="region" aria-label="Orders">
        <p class="note">Projected into the table's ng-content.</p>
      </OrdersTable>
    </main>
  )
}
day statepicked state
In the tag Vue (@qatjs/bridge-vue/island) Angular (@qatjs/bridge-angular/island)
a prop a Vue prop; what Vue does not declare falls through to its root an input (input() or @Input); anything else is an attribute of the host
on:x={fn} its emit x its output x
bind:x={v} v-model (bind:modelValue) a model() named x; bind:value on a ControlValueAccessor (Material's controls)
children the default slot; slot="name" for a named one projected into ng-content, by its select
  • Events. The handler gets the emitted value. The host element also dispatches it as a CustomEvent with that value as detail.
  • Types. qatjs check types each tag from the component's own types: Vue's $props, an Angular class's input, model and output fields. An event the component does not emit is an error, as is a value of the wrong type.
  • Angular. It runs zoneless, one application for the page. A local Angular component compiles for Angular's JIT, as the Angular CLI compiles one for JIT: typescript and @angular/compiler-cli are the app's dev dependencies.

The cost is said. qatjs compress prints each framework's runtime and the components that bring it (bridged: Vue 32.15 kB gzip for src/app.qx#VueDatePicker), and writes it to report.json (bridges). qatjs check --impact shows its change. A route whose only interactive content is bridged gets QX-BRIDGE-ONLY: it carries a framework for one component, and migrating it may pay. Every bridged tag is noted QX-BRIDGE-ISLAND (info).

On a server-rendered route the bridged component is always an island:

  • Vue: the server writes Vue's own SSR of it, and the island renders again with Vue when the page resumes.
  • Angular: the server writes its host, with the attributes it was given, aria-busy, and Angular renders it in the browser.

Streaming is not supported inside a bridged subtree. In qatjs dev, an edit of a local bridged component swaps its island; the page does not reload, and Qat's state stays.

What comes along, measured on examples/bridge-vue and examples/bridge-angular:

  • Vue's runtime: about 32 kB gzip.
  • Angular's: about 98 kB, compiled ahead of time. qatjs compress compiles the app's Angular components with ngtsc and links partially compiled packages (Material) with Angular's linker, as the Angular CLI does. No template is compiled in the browser, and @angular/compiler is not in the browser's bundle (it was 275 kB with it); a server build (dist/server/) still carries its template parser. qatjs dev keeps JIT: it compiles one file at a time.
  • The components' own code comes on top: a date picker, a Material table.

Markup as the browser reads it

A component's static markup is one HTML template, parsed by the browser. Four things follow:

  • HTML's nesting rules hold (QX-HTML-NESTING, an error): a <div> in a <p>, an <a> in an <a>, a <button> in a <button>, a cell outside a row. The browser would move such an element out as it reads the template, and the bindings below would not find their nodes. What a component or a block renders there is inserted as nodes, which nothing moves: <p><Chart /></p> is fine whatever Chart renders, and so are rows written directly in a <table>: the compiler writes the <tbody> HTML would put around them.

  • A state attribute's boolean is its word. aria-expanded={open} writes "true" or "false" (and nothing for null/undefined), as do the other ARIA attributes that take one (aria-pressed, aria-selected, aria-hidden, aria-disabled, aria-checked, …) and draggable, spellcheck, contenteditable. Every other attribute keeps HTML's booleans: disabled={busy} is present or absent.

  • A <select>'s value is set after its options, and again when they change: bind:value (or value={…}) with options from a {for} — a load's data, which arrives later — shows the state's option.

  • Props spread onto an element, <button {...rest}>, bind each key as if it were written out (@qatjs/core/spread); an attribute written after the spread wins.

  • Attributes are markup's names, not React's (QX-REACT-ATTR, an error with the fix-it): stroke-width, fill-rule, clip-path, xlink:href on SVG; aria-label, not ariaLabel; value and checked for what React calls defaultValue and defaultChecked; class and for. SVG's own camelCase names (viewBox, gradientUnits) and HTML's case-insensitive ones (tabIndex, readOnly) are as written. qatjs migrate writes the real names.

A component held in a state, a derived or a prop — let View = state(List) and <View /> — follows it: the tag compiles to <Dynamic component={View} />.

Accessibility: checked at compile time

The compiler checks the accessibility of what it can see in the markup, in .qx and in .tsx/ .jsx alike. The checks are conservative: anything it cannot see (a dynamic child {label}, a component, a custom element, a spread) counts as possibly accessible, so a check fires only on a certain problem. Each diagnostic comes with a fix-it (qatjs check --json, the editor's quick fix, eslint --fix).

diagnostic when fix-it
QX-A11Y-ALT (error) an <img> without alt alt="" (then describe the image, or keep it empty if it is decorative)
QX-A11Y-NAME (warning) a <button> or <a href> with no accessible name: no text, no dynamic child, no aria-label/aria-labelledby/title (an empty one is none), no <img alt="…"> inside aria-label="", to fill in: until you do, it still warns
QX-A11Y-CLICK (warning) on:click on a non-interactive element (div, span, li, p, section, img, …) without a role and without on:keydown/on:keyup/on:keypress role="button" tabindex="0" (then handle Enter and Space) — or use a <button>
QX-A11Y-LABEL (warning) an <input> (other than hidden, submit, button, reset, image), <select> or <textarea> with no aria-label/aria-labelledby/title (an empty one is none), not inside a <label> and not named by a <label for="id"> of the same file aria-label="", to fill in: until you do, it still warns
QX-A11Y-TABINDEX (warning) a static tabindex greater than 0 tabindex="0"
.qx15 lines, 1 reactive nameOpen in the playground
export default function Search({ results }) {
  let q = state('')
  return (
    <form role="search">
      <label for="q">Search</label>
      <input id="q" type="search" bind:value={q} />
      <button aria-label="Clear" on:click={() => (q = '')}>×</button>
      <ul>
        {for (const r of results)}
          <li key={r.id}><a href={r.url}>{r.title}</a></li>
        {/for}
      </ul>
    </form>
  )
}
q state

Suppress one with a qat-ignore comment naming the code (or its lint name), on the line or the line above — in JSX, inside braces:

.qx10 linesOpen in the playground
export default function Card({ open }) {
  return (
    <section>
      {/* qat-ignore QX-A11Y-CLICK — the whole card is a big target; its heading link is the keyboard path */}
      <div class="card" on:click={open}>
        <h2><a href="/item">Item</a></h2>
      </div>
    </section>
  )
}

// qat-ignore a11y-click works the same in script code; several codes may follow one qat-ignore. Configure them for the project in package.json, like every lint (off, warn or error):

JSON1 line
{ "qat": { "lint": { "a11y-name": "off", "a11y-tabindex": "error" } } }

The components of qat/ui compile with none of these diagnostics, and render with zero axe violations (WCAG 2.1 AA) in every state of examples/ui-gallery.