UI components
The standard for every Vue component in the apps and layers: where it lives, how it is named, its API and how it is tested. The blueprint behind it is nuxt-layers.md § 2; the kit itself is documented in nuxt-layer-ui.md.
Where components live
| Tier | What | Where | Native fallback |
|---|---|---|---|
| 0 Accessibility primitives | UiSkipLink, UiAnnouncer |
packages/nuxt-layer-base/app/components/a11y/ |
native only |
| 1 Primitives | one control or element: UiButton, UiInputText, UiSelect, UiIcon |
packages/nuxt-layer-ui/app/components/ui/UiX.vue |
required |
| 2 Composites | a few primitives with one job: UiForm, UiFormField, UiFormErrorSummary, UiFormActions, UiConfirmDialog, UiConfirmInline, UiUndoNotice |
packages/nuxt-layer-ui/app/components/ui/UiX.vue |
required |
| 3 Complex | data-heavy widgets: UiDataTable, UiChart, UiRichTextEditor |
packages/nuxt-layer-ui/app/components/ui/UiX/ |
the simplest semantic equivalent |
| App | portfolio views: AppStyleStudio, AppPrimaryNav, AppMediaFile / AppMediaFallback / AppPlaceholderMedia (media fallbacks) |
core/web/app/components/ |
— |
| Admin | admin views: AdminMediaDrawer, AdminNav |
core/admin/app/components/, packages/web-layer-admin/app/components/ |
— |
Logic lives in composables and utils; components are views. A component that both apps need goes into a layer, never into one app for the other to reach.
The four form parts (UiForm, UiFormField, UiFormErrorSummary, UiFormActions) render the same native markup in both
stacks; only the controls slotted into them differ. UiConfirmDialog renders through UiDialog, so it is PrimeVue’s Dialog
when PrimeVue is on and a native <dialog> when it is off. See Forms.
Folders
- Flat:
UiX.vuewith a scoped<style lang="scss">block. Use it while the component fits in one readable file. - Folder:
X/index.vue+X.scss+types.ts.index.vueloads the styles with<style lang="scss" src="./X.scss" scoped></style>(asAppStyleStudio/andUiImagedo).types.tsexportsXProps,XEmits,XSlotsandXExpose. Tier 3 components always use a folder.
Naming
Ui*: kit components (tiers 0–3). Generic, with no portfolio or admin wording, no app routes and no app colour names.App*:core/webviews.Admin*: admin views.- A
Ui*name says what it is (UiConfirmInline), not where it is used. - Files and components are PascalCase; slots, events and CSS classes are kebab-case; private script bindings used only by
the template start with
_.
API conventions
<script setup lang="ts">with a Pug template. In the template the PrimeVue branch comes first (v-if="isPrimeVue"), then the native branch (v-else).defineOptions({ inheritAttrs: false }), with$attrsbound on the element a caller means: the control itself, not a PrimeVue wrapper. Attributes that describe the value (aria-describedby,aria-invalid,aria-errormessage,aria-labelledby,aria-required) always reach the form control.- Props:
withDefaults(defineProps<…>()). Booleans default tofalse. Accessible names useariaLabel; icon-only controls require it. Ids useinputId, and anidattribute is carried through to the same control. v-modelisdefineModel(); the native branch writes it from the native event, the PrimeVue branch bindsv-model.- Emit only committed intent (
change,submit,retry). Don’t re-emit native events that$attrsalready forwards. - Slots are kebab-case; dynamic cell slots are
cell-<field>. - Every focusable component calls
defineExpose({ focus }), andfocus()lands on the interactive element in either stack. - Never pass a prop the component doesn’t declare. In the PrimeVue stack it may still render through
$attrs, but the native stack drops it.
Styling
- Scoped SCSS, rem / em / % units, em breakpoints via
bp-up()/bp-down()or container queries.:deep()only for library internals listed inDEEP_ALLOWED(core/web/tests/components-scss.spec.ts). - Colours come from the theme roles only (
docs/packages/theme.md#contrast-roles). Kit components read--theme-*-colornames, never--portfolio-*or--web-*; the ui layer’stests/colors-scss.spec.tsenforces this. - Every interactive element meets the touch floor (
--touch-target, 44px) in both directions, and text never goes below--type-min.
When a component may drop the native fallback
Tiers 0–2 always keep a native branch with the same props, v-model, accessible name and keyboard behaviour. A tier 3 component
may replace the PrimeVue look-alike with the simplest semantic equivalent when all of these hold:
- the equivalent is a native element that carries the same data and the same actions (a
<table>with sort buttons for a data table, that table for a chart, a markdownUiTextareafor a rich-text editor); - it works without JavaScript and during SSR;
- it keeps the component’s props and events, so callers don’t branch on the stack.
A component never falls back to nothing, and the fallback is recorded in the component’s JSDoc header and its docs page.
With features off
An app can turn the theme, the icons, PrimeVue and the media components off with tgmc: flags
(nuxt-layers.md § 1a). The accessibility floor stays in every mode:
- Icons off (
icon: false): an icon-onlyUiButtonshows itsariaLabelas visible text, the nativeUiChipremove button shows “Remove” (its accessible name staysRemove <label>), and a labelledUiIconrenders its label in a.sr-onlyspan. A decorativeUiIconrenders nothing. The loading spinner disappears, andaria-busystays. - PrimeVue off (
primevue: false): every kit component renders its native branch.UiToastHostrenders two live regions that exist before the first message,role="status"for info / success / secondary / contrast androle="alert"for error / warn, fed byuseAppToast()/$toastwith the samelifeas PrimeVue’s toast (default 3200 ms;0stays until dismissed). Each message has a “Dismiss” button (accessible nameDismiss <summary>) at least 44px in both directions, with thefocus-ringmixin. When a focused “Dismiss” removes its message, focus moves to the next message’s “Dismiss”, else the previous one, elsemain#main-content; it never falls to<body>. - Theme off (
theme: false): the native markup has nop-*styling (that lives in the theme stylesheet), so controls look like browser defaults plus each component’s scoped floors. Colours come from the CSS system colours in the fallback sheet. - Scoped floors: a component whose native markup the theme doesn’t fully style carries its own floors, so they hold with
the theme or icons off. The native
UiChipremove button is at least--touch-target(44px) in both directions, keeps text at--type-minor larger, and shows thefocus-ring-shadowring on:focus-visiblein every mode. - Tests:
tests/nuxt/ui-icon-off.spec.tsandtests/nuxt/ui-toast-host.spec.tsmount the icons-off and native-toast cases; thenuxt-layer-ui:nuxt-offproject (tests/nuxt-off/) mounts the kit with every flag off, including the forms template (ui-form-off.spec.ts) andUiConfirmDialog(ui-confirm-dialog-off.spec.ts). A component that adds an icon-only control or a new live region covers its features-off case there too.
Media that fails to load
Media slots and case studies show a labelled stand-in for a failed file; other kit images show an empty frame named by alt,
never a broken-image icon. The gallery video has no fallback yet (TODO).
- Kit.
UiImageandUiSvgImgemiterrorwhen the file fails (also when it failed before hydration) and swap the image for their#fallbackslot in the same frame; withfallbackLabelthe failed frame is named<fallbackLabel>: <alt>. Without a slot the frame stays empty, never a broken-image icon. - App.
AppMediaFile(any kind;AppMediaSlotuses it) showsAppMediaFallbackfor the kind when an image, svg, video or audio fails, or when a reference is unresolved (a document or model link is not probed). The case-study media keeps its own markup with the same rules. Other pages still callUiImage/UiSvgImgdirectly without a#fallback.
Details, names per kind and tests: site media § Fallbacks.
Lists and deletes
Four composables and two tier 2 components cover a list that pages, filters and deletes. The pure code is in
packages/nuxt-layer-ui/app/crud/ (export ./crud, Vue reactivity only, so plain Vitest drives it with fake timers); the
composables in app/composables/ add the announcer, focus and the route. The composables and both components are
auto-imported; the types come from @tgmc/nuxt-layer-ui/crud (CrudAdapter, ConfirmUndo, RouteQueryCodec …).
useConfirmUndo(options)
Confirm in place, then 8 s to Undo before the real delete. Options:
getId(item)anddescribe(item)(the name used in messages, quoted if it needs it:“Spring launch”,hero.png);hide(item)hides the item and returns a snapshot forrestoreandcommit; a throw cancels, nothing is pending;restore(item, snapshot)shows it again; on Undo, returningfalsekeeps it pending (the page says why, for example a full list); after a failed commit the return value is ignored;commit(item, snapshot)is the real delete;onCommitError(item, error)runs after a failed commit has restored the item;focusAfter(item, 'cancel' | 'undo' | 'commit')returns where focus goes (default: the element focused before the confirm step, if it is still in the page; otherwise the main landmark);delayMs(default 8000,UNDO_DELAY_MS),messages(deleted(label)→ “Deleted X.”,restored(label)→ “Restored X.”) andid(the prefix of the Undo button ids).
It returns confirmingId, pending (one { id, item, label, message, deadline, paused, buttonId, messageId } per delete that can
still be undone), committing (commit requests in flight), settling (something pending or committing), isPending(id),
undoButtonId(id), request(item), cancel(), confirm(item), undo(id), pause(id, source?) / resume(id, source?) (source
is 'pointer' or 'focus'; the window runs again once neither holds it) and flush().
- Confirm step.
requestswaps the control for the question; Cancel takes focus. Escape cancels and does not close a drawer or dialog around it. Cancel returns focus to the control that asked. - Undo window.
confirmhides the item, announces “Deleted X.” through the page’s announcer (useA11yAnnouncer) and focuses Undo. The 8 s stop while the line is hovered or holds keyboard focus (WCAG 2.2.1). The controller’s own focus on Undo does not hold the window. Undo restores, announces “Restored X.” and returns focus; when the window ends with focus on Undo, focus goes tofocusAfter(item, 'commit'). - Several at once. Each delete has its own line and timer.
- Commit points. The timer, a route leave and unmount all commit what is pending; a reload or closing the tab drops it
(owner Q2 A), because a browser lets a page do no async work there. A failed commit restores the item and calls
onCommitError. - Leave-guard order. Call
useConfirmUndo/useCrudResourceafter the page’s other leave guards (onBeforeRouteLeave,useUnsavedChangesGuard): vue-router runs leave guards in registration order and stops at the first that cancels, so a leave the page cancels commits nothing (a global guard that cancels later still leaves the flushed deletes committed).
UiConfirmInline and UiUndoNotice
UiConfirmInline is the question that takes the place of the control that asked (“Delete X? [Delete] [Cancel]”). Props: question
(required), confirmLabel (default “Delete”), cancelLabel (default “Cancel”), initialFocus ('cancel', the default, or
'confirm'). Events: confirm and cancel. It is a role="group" named by the question; Escape emits cancel and goes no
further.
UiUndoNotice lists the deletes that can still be undone (“Deleted X. [Undo]”), one line each, and renders nothing when there are
none. Props: undoable (the useConfirmUndo / useCrudResource().undoable controller; required), label (the list’s
name, default “Recently deleted”), undoLabel (default “Undo”) and holdSpace (default off). It is not a live region: the controller
announces through the page’s announcer, so the text is spoken once. Undo is described by its line (aria-describedby).
holdSpace: a line that leaves (committed or undone) keeps its space as a hidden row until the notice unmounts, so the 8 s commit never pulls the content below up under the reader. Held rows arevisibility: hidden,inertandaria-hidden="true"(not shown, read or focusable, even if a page overrides the visibility) and carry no ids; a new delete is added below them. Use it where the notice sits above content in a small scrolling area, like the media library’s phone sheet; a list page leaves it off.
UiConfirmInline(
v-if="undoable.confirmingId.value === post.id",
:question="`Delete ${post.title}?`",
@confirm="undoable.confirm(post)",
@cancel="undoable.cancel()"
)
UiButton(v-else, label="Delete…", severity="danger", variant="text", @click="undoable.request(post)")
UiUndoNotice(:undoable="undoable")
usePagedList(options)
“Load more” paging. Options: fetchPage({ offset, limit, signal }) returning { items, total? }, pageSize (default 24),
getId (drops rows a page repeats, so rows added elsewhere don’t show twice), announce(result) (the Load more wording),
onError(error, 'first' | 'more'), enabled(), key (a new value reloads from the first page), immediate (load on mount;
default on) and announcer (default on). It returns items, total (number | null), loading, loadingMore, loaded, error,
hasMore, status, load(), loadMore(), reset() and abort().
loadMore()resolves to the rows that arrived, ornullwhen nothing was fetched (not loaded, at the end, busy, failed), so the page can move focus when the button goes away.- Offsets count every row the list holds plus the rows a page repeated, so rows the page adds or removes itself keep paging aligned with the server.
- The default message is “Loaded 24 more, 72 of 120.” (
defaultLoadAnnouncement; “all 72 shown” or “72 shown” without a total). It goes to the announcer, and focus stays on the button. A page with its ownrole="status"line setsannouncer: falseand rendersstatus.
useCrudResource(adapter, options)
A paged list over a CrudAdapter with confirm + Undo deletes and create / update.
CrudAdapter<T, Id, F, C, U>:getId,list({ filter, offset, limit, sort?, signal }), and optionalget,create,updateandremove(id, { filter }).filterinremoveis the one the delete was confirmed under, so a delete confirmed in one database is committed there even if the page’s filter changed during the 8 s.- Options: the
usePagedListones (pageSize,announce,onError,announcer,immediate),filter(a ref or getter),enabled,sort,describe,onHidden(item)/onRestored(item)(a page closes and reopens its drawer here),onCommitError,focusAfter,delayMs,messagesandid. - Returns the paged list plus
rows(every loaded row) anditems(rowsminus pending deletes; pages showitems),selected(anId | null, cleared while its delete is pending and set again by Undo),undoable(theuseConfirmUndocontroller) andsave(null, input)/save(id, input)(create adds to the top ofrows; update replaces the row),reload()(commits the pending deletes, then loads the first page) anddispose()(aborts the request in flight; a load still waiting for a delete then fetches nothing;useCrudResourcecalls it on unmount). - Hidden rows stay in
rowsuntil their commit lands, so paging offsets stay aligned with the server;loadMore()does nothing while a delete request is in flight or a first page / reload is loading. loadingcovers the first page and every reload: it is true from the momentload()/reload()is called, while it waits for delete requests, until the new first page settles (Load more usesloadingMore).- A change of
filterorenabledrunsreload():loadingturns on at once, so a page that shows a loading line instead of its rows whileloading(the blog list, the media library) never shows the old filter’s rows during the commit.
useRouteQueryState(codec, defaults)
Filter state kept in the URL. codec has keys (the query keys it owns), read(query, defaults), write(state, defaults) (only values
that differ from the defaults), and optional isFiltered (default: write returns a key) and cleared (default: defaults);
firstQueryValue() reads the first value of a repeated key. It returns a ref per state key plus filtered and clear().
- A state change calls
router.replacefor the owned keys only: other keys and the hash stay, and no history entry is added, so Back leaves the page. - A URL change on the same path (Back / Forward, a link to the same page) updates the state; a change of path is ignored.
Differences from the blueprint
The kit follows nuxt-layers.md § 4 except where the pages needed more (the blueprint is read-only for this change; the owner updates it from this list):
hidereturns a snapshot (or throws to cancel),restoremay returnfalseon Undo to keep the item pending, andcommitgets the snapshot too.usePagedListalso takesgetId,onError,announce,enabled,announcerandimmediate; itskeyis optional,totalisnumber | null, andloadMore()returns the added rows.useCrudResourceaddsrowsbesideitems,describe,onHidden/onRestored/onCommitError,focusAfterandenabled;selectedis an id, not an item.useCrudResourcealso returnsreload()(commit the pending deletes, then load the first page; a filter change runs it) anddispose()(no load after unmount). Itsloadingis true from the momentload()/reload()is called until the new first page settles, including the wait for delete requests, not only while the page request runs.UiUndoNoticetakesholdSpace, which keeps the space of a line that left (hidden,inert) until it unmounts.- The package exports
./components/*(app/components/*), so another project’s tests import aUi*SFC by package name. CrudAdapter.removeisremove(id, { filter }).- The codec has optional
isFilteredandcleared, becauseuseBrowseQuery.clear()keepsviewanditemandfilteredignoresview.
Tests
Every kit component gets a mounted spec, packages/nuxt-layer-ui/tests/nuxt/ui-<component>.spec.ts, run by the
nuxt-layer-ui:nuxt Vitest project (mountSuspended against the layer running as a Nuxt app). Each spec covers:
- both stacks: every case runs with
runtimeConfig.public.theme.uiStackset to'primevue'and to'native'; v-modelround trip: a user change updates the model, and a new model value updates the control;- accessible name and
aria-*:ariaLabelnames the control,inputIdreaches a labelable control, andaria-describedby/aria-invalid/aria-labelledbyland on the control and nowhere else; - keyboard: the control is in the tab order (and leaves it when disabled), and the keys a user needs work (for example
ArrowDown / Enter on PrimeVue’s
Select); focus(): the exposed method movesdocument.activeElementto the control.
The lists and deletes code has a mounted spec for UiConfirmInline (ui-confirm-inline.spec.ts) and for each
composable (use-confirm-undo, use-paged-list, use-crud-resource, use-route-query-state), plus features-off
specs for UiConfirmInline and UiUndoNotice (tests/nuxt-off/ui-confirm-inline-off.spec.ts,
ui-undo-notice-off.spec.ts). Pure helpers get plain Vitest specs in packages/nuxt-layer-ui/tests/ (for the
crud code: confirm-undo, paged-list, crud-resource and route-query-state). Run everything with
npx nx run @tgmc/nuxt-layer-ui:test.
Helpers
tests/nuxt/support/ui-stack.ts:UI_STACKS;setUiStack()writesruntimeConfig.public.theme.uiStackbefore a mount;mountIn()mounts attached to the document;mountModel()is av-modelhost that records the updates;cleanUpMounted()goes inafterEach;exposedFocus()returns a mounted component’s exposedfocus().tests/nuxt/support/control-matrix.ts:describeControlMatrix(name, { component, props, control, labelable })registers the shared cases for a form control (markup per stack, accessible name,aria-*routing, tab order,focus()). The spec adds its ownv-modeland keyboard cases.invalid: trueadds the case that theinvalidprop givesaria-invalid="true"and thep-invalidclass; set it when a control declares that prop.tests/nuxt/support/dialog-shim.ts:installDialogShim(), called at module top level by every spec that mounts a native<dialog>. jsdom hasHTMLDialogElementbut noshowModal()orclose(), so the nativeUiDialogwould throw on open. The shim sets and clearsopen, dispatchesclose, and throwsInvalidStateErrorfromshowModal()on a detached dialog, as browsers do. It has no top layer, no focus moves and no Escape handling, and@vue/test-utilsstubs<transition>, so PrimeVue’s enter / leave focus hooks don’t run either. That is whyUiConfirmDialogfocuses Cancel itself and handles Escape on its own root, and why native Escape and the backdrop tap are checked in a browser.- Navigation in mounted specs: Nuxt’s
navigation-repaintplugin delays every navigation that passes the guards by a timer, so oneflushPromises()never sees the new route. Wait for it withvi.waitFor; to prove a navigation was stopped, wait more than 100 ms before checking that the route didn’t change. - Covered today:
UiImagefailure fallback (tests/nuxt/ui-image.spec.ts) andUiSvgImg(tests/nuxt/ui-svg-img.spec.ts), both stacks;UiButtonand the six form controls (UiInputText,UiTextarea,UiPassword,UiSelect,UiCheckbox,UiToggleSwitch), with theinvalidcase forUiInputText,UiTextareaandUiSelect;- the forms template:
tests/nuxt/ui-form.spec.ts(both stacks) andtests/nuxt-off/ui-form-off.spec.ts, plus jsdom specs for the pure code (tests/form-errors.spec.ts,tests/form-values.spec.ts,tests/form-controller.spec.ts); UiConfirmDialog:tests/nuxt/ui-confirm-dialog.spec.ts(both stacks) andtests/nuxt-off/ui-confirm-dialog-off.spec.ts;- the leave guard:
tests/unsaved-changes.spec.ts(the prompt’s decisions) andtests/nuxt/unsaved-changes-guard.spec.ts(mounted, both stacks); - part of
UiDialog:tests/nuxt/ui-dialog.spec.tscoversrole, opening when mounted visible, followingvisible, and the native backdrop only.
The other 22 components, and the rest of
UiDialog, are tracked by name in the TODO list and get a spec when each is next touched.
UiButton
packages/nuxt-layer-ui/app/components/ui/UiButton.vue. The same props work in both stacks: the PrimeVue stack renders
Button, the native stack a <button> / <a> with the same classes.
| Prop | Type | Notes |
|---|---|---|
label |
string |
Visible text. |
icon |
Lucide name | Decorative; an icon-only button needs ariaLabel. |
ariaLabel |
string |
The accessible name of an icon-only button. |
severity |
secondary, success, info, warn, danger, contrast, help |
Primary when unset. |
variant |
outlined, text, link, ghost |
ghost is text plus the hover wash. |
size |
sm, md (default), lg |
Padding only. PrimeVue’s small / large are not valid values. |
loading |
boolean |
See the rules below. |
to |
route location | Renders a NuxtLink. |
href |
string |
Renders an <a>. |
external |
boolean |
With href or to: opens a new tab. |
flat |
boolean |
Flat solid fill; automatic inside forms, search and field groups. |
type |
button (default), submit, reset |
Never rendered on a link. |
disabled |
boolean |
Never rendered as the disabled attribute on a link. |
Rules:
sizechanges padding only, and every size keeps the 44px height.- Icon-only buttons are 44px wide and need
ariaLabel. loadingkeeps focus, setsaria-busy/aria-disabled, ignores clicks and blocks form submission; its spinner turns only when motion is allowed.torenders aNuxtLinkandhrefan<a>, never withtype/disabled.externalopens a new tab withrel="noopener noreferrer"and a visually hidden “(opens in a new tab)” (the theme’s.sr-only).- A disabled link drops
hrefand becomesrole="link"+aria-disabled="true". loadingis ignored on links.flat(or a flat context: aform,[role="search"],.p-inputgroup,[data-field-actions]) paints the theme’sbutton-flatrecipe: no gradient, text-shadow or lift; plain primary and secondary get the flat fills, other severities keep their own fill; the focus ring stays. Filled status buttons (success,warn,danger,info) paint the theme’s status hue with the paper label on every branch, includingto/hreflinks.- Pass only declared props. In the PrimeVue stack an undeclared prop (
text,rounded,size="small") falls through$attrsand still renders, but the native stack drops it.core/web/tests/ui-button-call-sites.spec.tswalks everyUiButton(…)in the apps and layers and fails on:- an attribute that is neither a declared prop, a directive or event, an
aria-*/data-*attribute, nor one of the plain pass-through attributes (class,style,id,key,ref,title,name,form,download,tabindex,role,autofocus); - a static value that a literal-union prop doesn’t accept, such as
size="small".sizeis declared, so the name check alone can’t see it; the guard reads the unions (size,variant,severity,type) fromUiButton’sdefineProps.
- an attribute that is neither a declared prop, a directive or event, an
//- Button
UiButton(label="Save", @click="save")
//- Icon-only: the name goes on the button
UiButton(icon="x", variant="text", aria-label="Close details", @click="close")
//- Loading: stays focusable, and a submit button won't submit twice
UiButton(type="submit", label="Save", :loading="saving")
//- Internal link (client-side navigation)
UiButton(to="/admin/blog", label="Back", variant="outlined")
//- External link (new tab, announced)
UiButton(href="https://example.com/deck.pdf", label="Download deck", icon="file-text", external, download)
UiTabs
packages/nuxt-layer-ui/app/components/ui/UiTabs.vue: PrimeVue Tabs when PrimeVue is on, otherwise a native role="tablist" with the same p-tabs / p-tab classes. Used by the evidence-examples dialog (AppEvidenceExamplesDialog) and /product; core/admin has none. The theme styles both stacks as plain tabs (ink-muted labels, the selected one ink, bold and underlined in --theme-link-color, 44px, focus ring, forced-colors Highlight): see theme.md § Tabs.
UiDialog
packages/nuxt-layer-ui/app/components/ui/UiDialog.vue. PrimeVue’s Dialog when PrimeVue is on, otherwise a native
<dialog class="p-dialog p-component"> with the same props: visible (v-model:visible), header, ariaLabel, role
(dialog by default, or alertdialog), modal (default true), closable (default true) and dismissableMask (default
true). It has a default slot and a footer slot. Other attributes, such as aria-describedby, go on the dialog root.
- Look (
core/web):.p-dialoginassets/css/_globals.scssuses the themeglass-overlaymixin without the blur, so every dialog floats with the raised--shadow-lgand aCanvasTextborder in forced-colors mode (theme.md § Elevation). rolereaches the dialog root in both stacks. PrimeVue hard-codesrole="dialog", and the forwarded value overrides it.- Native stack: the dialog opens with
showModal()when it is mounted withvisibleset, and then followsvisibleboth ways. Escape fires the nativecancelandcloseevents, which setvisibletofalse. - Native backdrop: with
dismissableMaskon, a click on the backdrop closes the dialog, as PrimeVue’s mask does. It closes only when the press and the release both land on the backdrop, so pressing inside the box (to select text, for example) and releasing outside keeps it open. A click inside the box, padding included, never closes it. A caller that must not close on the backdrop passes:dismissable-mask="false". - Inside the native dialog, a
<button>withouttype="button"submits the dialog’sform(method="dialog")and closes it. - Focus: after opening, PrimeVue focuses the first
[autofocus]element once its enter transition ends, andshowModal()does the same natively. On close, both return focus to the element that was focused when the dialog opened.
Forms
The forms template is four tier 2 parts and one composable. UiForm, UiFormField, UiFormErrorSummary and UiFormActions
read the controller that useForm() returns. The schema can be any Standard Schema; the apps use zod 4. The admin blog editor
(packages/web-layer-admin/app/pages/admin/blog/[id].vue) is the reference page. The design, and why the layer doesn’t use
@primevue/forms, are in nuxt-layers.md § 3.
UiForm(:form="form", aria-labelledby="post-form-title")
UiFormErrorSummary
UiFormField(name="title", label="Title", required, v-slot="{ field, invalid }")
UiInputText(v-bind="field", :invalid="invalid")
UiFormField(name="body", label="Body", hint="Markdown", required, v-slot="{ field, invalid }")
UiTextarea(v-bind="field", :invalid="invalid", :rows="16")
UiFormActions
UiButton(type="submit", label="Save", :loading="form.pending.value")
UiConfirmDialog(v-bind="leavePrompt.dialog.value")
const form = useForm({
id: 'post',
schema: blogPostCreateSchema,
initialValues: { title: '', slug: '', excerpt: '', body: '', status: 'draft' },
async onSubmit(values, { signal }) {
const saved = await adminFetch<BlogPost>(`/api/admin/posts/${id}`, { method: 'PUT', body: values, signal });
for (const name of FIELDS) form.rebase(name, saved[name]);
},
});
const leavePrompt = useUnsavedChangesGuard(form.dirty, {
allow: (to) => deleted.value || isAdminSignInPath(to.path),
focusOnStay: () => document.getElementById('post-title'),
});
The parts
UiForm(propform, required) rendersform.ui-formwith the controller’sid,novalidate(the schema validates, not the browser) andaria-busy="true"while a submit is pending. Submitting runsform.handleSubmit. Other attributes, such asaria-labelledby, go on the<form>.UiFormField(propsname,label,hint,required) renders the label (<fieldId>-label,forthe control), an optional hint (<fieldId>-hint) and, while the field has an error, its first message (<fieldId>-error): thecircle-alerticon, a visually hidden “Error: “ and the message, which wraps anywhere. The “(required)” marker is hidden from screen readers; the control getsaria-required="true"instead. The root carriesdata-field-name, plus.ui-form-field--invalidwhile the field has an error. Its default slot receives{ field, invalid }:fieldis safe to bind on any control:id,name,modelValue,onUpdate:modelValueandonBlur, plusaria-labelledby(the label),aria-describedby(the hint and the error, whichever exist; absent when neither does),aria-invalid="true"while the field has an error, andaria-required.aria-labelledbyalso names controls that a<label for>can’t, such as the<span role="combobox">of PrimeVue’sUiSelect.invalidis a boolean for controls that declare aninvalidprop. Today these areUiInputText,UiTextareaandUiSelect, where it givesaria-invalid="true"and thep-invalidclass in both stacks. Never bindinvalidto any other control (see “never pass a prop the component doesn’t declare” above).
UiFormErrorSummary(no props) goes first in the form. After a failed submit it shows a heading with the count (“There is 1 problem with this form” or “There are N problems with this form”), the form-level message if there is one, and one link per field error with that field’s first message. A link focuses its control without changing the URL. The summary’s id is<formId>-summary, withtabindex="-1"so it can take focus.UiFormActions(proplabel, default “Form actions”) is a labelled group for the buttons, primary first, and a visible status line showingform.statusMessage(“Saving…”, then the saved text). The line isn’t a live region, because the announcer speaks the same words.
All four throw “<Component> must be used inside UiForm” when they are rendered outside a UiForm.
useForm(options)
Auto-imported from the ui layer. The types and createFormController (the same controller without Nuxt) come from
@tgmc/nuxt-layer-ui/forms. Options:
schema: any Standard Schema v1 for a record of values.initialValues: values of the schema’s input type. They are also the first baseline thatdirtycompares against.id: the prefix of the form and field ids. A field’s id is${id}-${name}, with dots in the name turned into dashes. The default isuseId(). The blog usespost, which keeps its ids#post-title,#post-slugand so on.validateOn: default{ initial: 'submit', afterError: 'change' }. Nothing is flagged while someone tabs through an empty form; after a failed submit, each field checks itself again as it changes.initial: 'blur'also checks a field when it loses focus. Each field keeps only its latest check, and checks on different fields never cancel each other (the blog’s slug follows the title, so one keystroke checks both). A submit,reset()orvalidate()with no name drops the field checks still running.onSubmit(values, { signal }): receives the schema’s output (trimmed, normalised, defaults applied). Throw to fail.signalaborts whenabort()is called or the component’s scope is disposed.mapServerError(error): turns a thrown error into{ fieldErrors, formError }. The default isreadServerFormError(error, 'The form could not be saved. Try again.'). Returnnullwhen something else handles the error, such as a 401 that signs the user out: the form then shows nothing and moves no focus.announce: the{ saving, saved }texts, “Saving…” and “Saved” by default. They are read each time they are used, so getters work (the blog says “Post created.” or “Post saved.”).falsesilences the saving and saved announcements; the error count is always announced.
It returns the controller: id, values, errors, formError, touched, dirty, pending, status (idle, invalid,
pending, saved or failed), statusMessage, submitCount, errorCount (fields with an error, plus one for a form-level
error), fieldId(name), error(name) (the first message), field(name), handleSubmit(event?), validate(name?),
setErrors(errors), reset(values?), rebase(name, value), focusFirstInvalid() and abort().
What a submit does:
- A submit while another is pending is ignored.
pendingturns on before the schema runs, so the button is busy from the first click even while an async schema validates. Fields stay editable. - Invalid values: the errors are set,
statusbecomesinvalid, the count is announced, and after the next render focus moves to the first invalid field. If that field isn’t on the page, or there is only a form-level error, focus goes to the summary. - Valid values:
statusbecomespending, and “Saving…” is shown and announced. WhenonSubmitreturns,statusbecomessaved. onSubmitthrows:mapServerErrormaps the error, and when the result has nothing readable the default message is used.statusbecomesfailed, with the same announcement and focus move as invalid values.
“Saved” needs a clean form. statusMessage shows the saved text only while the form isn’t dirty, and the announcer skips
“Saved” when the form is still dirty after onSubmit returns. So after a successful save the page adopts what the server
saved: form.rebase(name, savedValue) for each field (the server may normalise a value, as it does the slug), or
form.reset(saved). A page that does neither never shows or announces “Saved”. The next edit hides the line again.
rebase(name, value)makesvaluethe field’s baseline. The field takes the value too, unless the user changed it while the save was in flight.reset(values?)sets a new baseline and clears the errors, the touched fields, the submit count and the status. Without an argument it returns to the last baseline. Field checks that are still running are dropped.- Values: plain objects and arrays are deep-copied and compared by content, a
Dateis compared by its time, and any other object (aFile, a class instance) is kept by reference and compared by identity.
Server errors (422 and 409)
@tgmc/nuxt-layer-ui/form-errors (packages/nuxt-layer-ui/shared/form-errors.ts) holds what client and server share. It has no
Vue and no DOM, so Nitro handlers import it too:
FieldErrors(Record<string, string[]>, keyed by dot path such aslinks.0.url) andServerFormError({ fieldErrors?, formError? });issuesToErrors(issues), which groups Standard Schema issues by field; an issue without a path becomesformError;readServerFormError(error, fallback), which reads a failed$fetch;errorSummaryHeading(count), the summary heading and the announcement.
A write handler throws createError({ statusCode: 422, statusMessage, data: { fieldErrors, formError } }). Nitro puts data
inside its JSON error body, and ofetch puts that body at error.data, so readServerFormError reads error.data.data.
Without that payload it falls back to the response’s status message, then the error’s, then fallback. Keep statusMessage
ASCII, because h3 strips any other character from it; the full text travels in data. The admin blog API’s contract (422 for
invalid fields, 409 on fieldErrors.slug, 404 and 400 on formError) is in admin.md § Write errors.
Unsaved changes: the leave dialog
const leavePrompt = useUnsavedChangesGuard(form.dirty, { allow, focusOnStay });
Then render UiConfirmDialog(v-bind="leavePrompt.dialog.value") once in the page template. The guard returns
{ open, stay, leave, dialog }; dialog carries visible, the texts and the onConfirm / onCancel listeners.
- While the form is dirty, an in-app navigation to another path opens “Leave without saving?” with the message “You have
unsaved changes on this page. If you leave now, they are lost.” and the buttons Stay and Leave (danger). The options
header,message,stayLabelandleaveLabelreplace these texts. A clean form never asks, and neither does a navigation that changes only the query or the hash. - Stay is the default. It is focused first, and Escape, a backdrop tap or any other close of the dialog also mean Stay.
Focus then returns to the element that started the navigation. When that element is gone, or nothing had focus, focus goes to
focusOnStay(), otherwise tomain#main-content, otherwise to the page’s firstmain. Thatmaingetstabindex="-1"when it has no tabindex, as the skip link’s target does, so focus never falls to<body>. - Leave lets the navigation through, and every later navigation too until the page unmounts, so a redirect from route middleware after Leave doesn’t ask again. The trade-off: if a navigation is aborted after Leave without a redirect, the page stays and later navigations no longer ask.
allow(to)lets chosen destinations (to.path) go without asking. It is read at navigation time, so a ref set just beforenavigateToworks. The blog page passesallow: (to) => deleted.value || isAdminSignInPath(to.path), so neither the forced sign-in redirect after a 401 nor the return to the list after a delete asks.- The guard registers both
onBeforeRouteLeaveandonBeforeRouteUpdate, because/admin/blog/newand/admin/blog/:idshare one route record: going from one to the other is a route update. After a create, the blog page callsform.reset(created)beforenavigateTo, so the form is clean and nothing asks. - Navigations started while the dialog is open share its answer. One navigation can reach the guard twice (in apps without pages, Nuxt’s minimal router runs both hooks); the second call gets the answer already given.
- Unmounting while the dialog is open answers Stay without moving focus.
- Reload and closing the tab get the browser’s own prompt, because browsers allow no custom dialog there. The
beforeunloadlistener is attached only while the form is dirty and is removed on unmount.
UiConfirmDialog
A yes / no question in a modal alertdialog, rendered through UiDialog. Props: visible (required; the parent owns it),
header, message, confirmLabel (default “Confirm”), cancelLabel (default “Cancel”) and confirmSeverity (danger, the
default, or contrast). Events: confirm and cancel.
role="alertdialog", named by the header and described by the message. It has no close button and no icons.- Cancel comes first and takes focus when the dialog opens. Escape, a backdrop click or any other close emits
cancel. - Each opening answers once: at most one
confirmorcancel. One Escape reaches both the dialog’s own handler and the stack’s close, and still gives onecancel. The parent setsvisibletofalseon either event. - Both buttons are
type="button", so neither submits the native dialog’s form.
UiConfirmDialog(
:visible="asking",
header="Discard this draft?",
message="The draft is deleted for good.",
confirm-label="Discard",
@confirm="discard",
@cancel="asking = false"
)
Responsive, keyboard, screen reader and touch
- Responsive: every part is a grid or a wrapping flex row with
min-width: 0, so nothing overflows at 375px. Long error and dialog messages wrap anywhere, and the dialog’s buttons wrap at 375px. - Touch: summary links and all buttons meet the 44px touch floor, and nothing depends on hover.
- Keyboard: a failed submit moves focus to the first invalid field (or the summary), summary links focus their control, the dialogs open with Stay or Cancel focused, Escape answers them, and focus returns after Stay.
- Screen readers: the error count, “Saving…” and the saved text are announced through
UiAnnouncer, the form isaria-busywhile it saves, and each control is named by its label and described by its hint and error. - Not colour alone: an error has the
circle-alerticon (when icons are on), the visually hidden “Error:” prefix,aria-invalidand a start border. With the theme off,--theme-error-ink-colorfalls back toCanvasText.