Nuxt template layers: architecture blueprint
Companion to the roadmap 2026-10-14-ui-template-revision.md. Task briefs point at the section that applies to them. Items marked “verify” were not confirmed against source. This is a design blueprint: where it differs from shipped code, the code and the package docs (nuxt-layer-base.md) win.
1. Layer topology
packages/nuxt-layer-base @tgmc/nuxt-layer-base (no PrimeVue)
nuxt.config.ts modules @nuxt/a11y, src/module/tgmc-features.ts; Sass injection; icon/a11y defaults
src/config/{a11y,icons,scss,features,feature-packages,index}.ts
src/module/ tgmc-features.ts (`tgmc:` flags; installs @nuxt/icon), theme-fallback.ts,
feature-off.ts, kit.ts (export "./module-kit")
scss/ _fallback.scss, fallback.css (theme-off fallback; export "./scss/fallback")
app/components/a11y/ UiSkipLink, UiAnnouncer, UiVisuallyHidden
app/composables/ useA11yAnnouncer, useFocusTrap, useInertOutside, useMatchMedia,
usePrefersReducedMotion
app/utils/ focus-trap.ts, inert-outside.ts (single copies)
src/runtime/motion.ts MOTION_PREFERENCE_STATE_KEY ('tgmc-motion'), export "./motion"
packages/nuxt-layer-ui @tgmc/nuxt-layer-ui (extends ['@tgmc/nuxt-layer-base'])
nuxt.config.ts src/module/tgmc-ui.ts (installs @primevue/nuxt-module); primevue config;
components dir
src/config/primevue.ts moved from core/web/config-properties (export "./primevue")
src/config/prime-components.ts the Prime* names stubbed when PrimeVue is off
app/components/ui/ 39 Ui* (UiCodeBlock stays in core/web), including the forms parts, UiSelectButton, UiConfirmInline and UiUndoNotice
(UiForm, UiFormField, UiFormErrorSummary, UiFormActions) and
UiConfirmDialog — shipped; the data / editor / upload components below
are planned
app/components/media/ registered only with `tgmc.media` (empty until the media components land)
app/feature-plugins/ toast-primevue.client.ts or toast-native.client.ts ($toast; added by the
ui module, not auto-scanned)
app/composables/ shipped: useUiStack, useAppToast (export "./toast"), useForm,
useUnsavedChangesGuard;
planned: useCrudResource, useConfirmUndo, usePagedList,
useRouteQueryState, useUploadQueue, useChartTheme
app/forms/ form-values.ts, form-controller.ts (export "./forms"), unsaved-changes.ts:
plain TypeScript on Vue reactivity, not auto-scanned
app/utils/ planned: upload-queue.ts, chart-colors.ts, markdown-policy.ts
shared/form-errors.ts error shapes and readers, no Vue or DOM (export "./form-errors")
- Keep editor and charts inside the UI package; heavy dependencies load inside their components (
import()inonMounted). - The empty, auto-loaded
core/web/layers/1.basewas removed (owner-accepted);@tgmc/nuxt-layer-basereplaces it. - Extends chain (a single path to each layer, no diamond):
core/webextends['@tgmc/nuxt-layer-ui'], and drops@nuxt/icon,@nuxt/a11yand@primevue/nuxt-modulefrom its ownmodules.packages/web-layer-adminextends['@tgmc/nuxt-layer-ui'].core/adminextends['@tgmc/web-layer-admin'], and drops its cross-appcomponents/imports.dirspaths (after auditing which web composables it uses), its../web/config-properties/primevue-propimport, its ownscss.additionalDataand its base icon list.
- defu merge: arrays concatenate, but functions replace. The base layer therefore owns the single Sass
additionalData:
export function tgmcScssAdditionalData(extraUses: string[] = []) {
const header = ['@use "pkg:@tgmc/theme/scss/nuxt-auto" as *;', ...extraUses].join('\n');
return (source: string, filename: string) =>
!filename.includes('.vue') || filename.includes('node_modules') || source.includes('nuxt-auto')
? source
: `${header}\n${source}`;
}
- Theme Sass without
../../:- Use
NodePackageImporter, imported from whichever Sass implementation Vite loads. - Add a theme export
"./scss/nuxt-auto": { "sass": "./scss/_nuxt-auto.scss", "default": "./scss/_nuxt-auto.scss" }. - Load paths:
dirname(createRequire(import.meta.url).resolve('@tgmc/theme/package.json')).
- Use
- Dependencies:
| Package | Placement in base | Placement in ui |
|---|---|---|
nuxt, vue |
peer | peer |
@nuxt/kit |
dep ^4.5.2 |
dep ^4.5.2 |
@nuxt/icon |
optional peer ^2.5.1 |
via base |
@nuxt/a11y |
dep, root’s resolved version | via base |
@iconify-json/lucide |
optional peer, root range | via base |
@tgmc/theme |
optional peer * |
dep * (UiImage, PrimeVue preset) |
@tgmc/utilities |
dep * |
via base |
primevue, @primevue/nuxt-module |
— | optional peer "4" |
@tgmc/media-client, @tgmc/media-player |
— | optional peer * |
@primeuix/themes |
— | via @tgmc/theme |
chart.js |
— | dep ^4 |
@tiptap/vue-3, @tiptap/pm, @tiptap/starter-kit, @tiptap/extensions, @tiptap/markdown |
— | dep |
@standard-schema/spec |
— | dep ^1.1.0 (types only) |
zod |
— | devDep ^4.6.7 (apps own schemas; web-layer-admin dep) |
@primevue/forms |
— | not adopted |
Add a guard: layer dependency ranges must equal the root ranges. core/web/tests/layer-dependency-ranges.spec.ts checks dependencies, devDependencies and peerDependencies, and that every feature package is an optional peer (never a dependency).
An optional peer isn’t installed for the app. Each app declares the packages of the features it keeps on, as generated apps do (§ 1a). core/web and core/admin therefore list primevue and @primevue/nuxt-module ("4") in their own dependencies: with the packages only in the root’s devDependencies and an optional peer of the ui layer, npm marks PrimeVue devOptional in the lockfile, and a production install (--omit=dev) would leave it out.
- Guard retarget:
- Add
core/web/tests/support/ui-source-roots.ts:['core/web/app', 'packages/nuxt-layer-base/app', 'packages/nuxt-layer-ui/app']. components-scss,colors-scss,ui-floorsandiconswalk every root. Each root must produce at least one file, stale allowlist entries fail, and allowlist keys become repo-relative.- Shared icon list in
packages/nuxt-layer-base/src/config/icons.ts(TGMC_BASE_ICONS). The icon test checks names against the base list plus the app list. This changes the documented icon rule (needs owner approval).
- Add
- Per layer:
- Nx targets
build(nx:noop),lintandtest; eslint.config.jswitheslint-plugin-vue-pug;- a Prettier Pug config;
vitest.config.ts;"type": "module";- included in
npm test(verifyscripts/test-web.sh).
- Nx targets
1a. Optional features
An app turns layer features off in nuxt.config.ts; every flag defaults to true:
export default defineNuxtConfig({
extends: ['@tgmc/nuxt-layer-ui'],
tgmc: { theme: true, icon: true, primevue: true, media: true },
});
| Flag | Layer | Off means |
|---|---|---|
theme |
base | No @tgmc/theme stylesheet or Sass. scss/fallback.css gives the theme names the layers read, with CSS system colours, and SFC styles get scss/_fallback.scss (the focus mixins). |
icon |
base | @nuxt/icon isn’t installed; <Icon> is a null stub. Icon-only controls show their accessible name as text. |
primevue |
ui | @primevue/nuxt-module isn’t installed; Prime* tags are null stubs; the kit renders native markup; $toast feeds UiToastHost’s native list. Needs theme. |
media |
ui | app/components/media isn’t registered; @tgmc/media-client / @tgmc/media-player needn’t be installed. A base-only app ignores primevue and media. |
- The flags are read by
src/module/tgmc-features.ts(base,configKey: 'tgmc') andsrc/module/tgmc-ui.ts(ui), which stand where@nuxt/iconand@primevue/nuxt-modulestood in the module lists, so an all-on app builds exactly as before (core/webandcore/adminbuild the same CSS). Nuxt generates thetgmc?:type onNuxtConfigfrom the module; there is no hand-written augmentation. The base module publishes the resolved flags asappConfig.tgmc, and runtime code reads them withuseTgmcFeatures()(a computed ref with every missing flag on). - A switched-on feature whose packages aren’t installed fails the build with the package names and the flag that turns it off. The feature packages are optional peers of the layers, so the app declares the ones it keeps on.
{ primevue: true, theme: false }fails the build: the PrimeVue preset reads the theme’s custom properties.theme: falsefails for an app that points#tgmc-theme-stylesheetat its own sheet or replacesadditionalDatawith its own function (pass extra@uses totgmcScssAdditionalData()instead).core/webandcore/adminpoint the alias at their own sheet, so they keep the theme on.- A stub is one null component (
src/runtime/feature-off.tsin the base layer) registered under each name, so templates that still name<Icon>or aPrime*tag resolve with no Vue warning and render nothing.isCustomElementisn’t used because severalPrime*tags take slot templates, which would render as stray markup. - Contract:
packages/nuxt-layer-base/tests/fallback-contract.spec.tskeeps the fallback’s names in the theme and covering everything the layers and generated templates use. The SFC contract (nuxt-auto) has no breakpoint or floor mixins; layers usevar(--touch-target)/var(--type-min)and container oremmedia queries directly. The fallback’s shadows are empty shadows (0 0 0 0), notnone, because the layers list them after a focus ring andnonein a list drops the ring. The fallback has no document reset (nobox-sizing: border-box, the browser’sbodymargin stays), so a layer or template box that setswidth: 100%and padding also setsbox-sizing: border-box. The shared colour guard (core/web/tests/colors-scss-guard.spec.ts) flags CSS system colours in component and page styles; only the fallback sheet,var()fallbacks and@media (forced-colors: active)blocks may use them. - Proof:
npx nx run @tgmc/nuxt-layer-ui:test:build-matrixbuilds an all-on and an all-off fixture app and checks what each installed, registered, bundled and rendered (CI runs it for affected PRs;npm testdoesn’t).
2. Standard component structure
| Tier | Examples | Shape | Native fallback |
|---|---|---|---|
| 0 Accessibility primitives (base) | UiSkipLink, UiAnnouncer, UiVisuallyHidden | .vue |
native only |
| 1 Primitives | UiButton, UiInputText, UiSelect | ui/UiX.vue |
required (useUiStack) |
| 2 Composites | UiFormField, UiForm, UiConfirmDialog, UiDrawer, UiConfirmInline, UiUndoNotice | ui/UiX.vue |
required |
| 3 Complex | UiDataTable, UiChart, UiRichTextEditor, UiMultiUpload, UiCrudView | ui/UiX/index.vue + UiX.scss (<style src scoped>) + types.ts |
simplest semantic equivalent |
The working standard derived from this section is UI components. UiVisuallyHidden doesn’t exist yet: until it does, the theme’s .sr-only class covers it (UiButton’s new-tab note uses it).
Tier 3 fallbacks (each also covers no-JS and SSR):
- UiDataTable: a native
<table>with sort buttons in the headers. - UiChart: that data table.
- UiRichTextEditor: a markdown
UiTextarea. - UiMultiUpload: always native; it does not use PrimeVue FileUpload.
App* / Admin* components stay in the apps. Logic lives in composables and utils; components are views.
Code conventions:
types.tsexportsUiXProps,UiXEmits,UiXSlotsandUiXExpose, re-exported fromshared/types.ts.defineOptions({ inheritAttrs: false })withv-bind="$attrs"on the interactive root;withDefaults(defineProps<…>());defineModel; typeddefineEmits/defineSlots;defineExpose({ focus })on every focusable component.- In the Pug template, the Prime branch comes first, then the native branch.
sizechanges only padding and font size;min-height: var(--touch-target)holds for every size.- Booleans default to
false. Accessible names useariaLabel, and icon-only controls require it. - 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>. :deep()only for library internals. Add the PrimeVue DataTable, Chart and ProseMirror wrappers toDEEP_ALLOWED.
UiButton:
interface UiButtonProps {
label?: string;
icon?: string;
ariaLabel?: string;
severity?: 'secondary' | 'success' | 'info' | 'warn' | 'danger' | 'contrast' | 'help';
variant?: 'outlined' | 'text' | 'link' | 'ghost';
size?: 'sm' | 'md' | 'lg';
loading?: boolean; // aria-busy + aria-disabled, stays focusable, clicks ignored
to?: RouteLocationRaw;
href?: string; // NuxtLink / a with p-button classes
external?: boolean; // target=_blank + visually hidden "(opens in a new tab)"
type?: 'button' | 'submit' | 'reset';
disabled?: boolean;
}
loading is ignored on links (to / href).
Testing:
- Pure utilities: Vitest in the node environment.
- Components:
@nuxt/test-utils(environment: 'nuxt',mountSuspended) plus@vue/test-utils.- Matrix:
uiStackset to'primevue'and to'native';v-modelround trip; accessible name andaria-describedby/aria-invalidwiring; keyboard behaviour;focus().
- Matrix:
- End to end: Cypress specimens on
/styles/parity, plusui-audit.cy.ts.
Docs:
docs/packages/nuxt-layer-ui.md: a table of tiers 1 and 2.docs/packages/nuxt-layer-ui/<ui-x>.md: one page per tier 3 component.- Catalog entries in
docs/README.mdanddocs/_catalog.md. - Keep the JSDoc header in each SFC.
3. Forms: in-house useForm on Standard Schema (zod 4)
Why not @primevue/forms:
- It breaks the native fallback, because fields register through PrimeVue’s form injection.
- Custom fields (editor, upload) would need adapters.
- It provides no error summary and no server error mapping.
Shipped in PR 3. The working reference (examples, every option, the leave dialog, tests) is UI components § Forms; this section keeps the design.
Where the code lives. Nuxt auto-imports every export of a layer’s app/utils and app/composables, and server code
mustn’t import app/ files, so the pure code sits elsewhere:
packages/nuxt-layer-ui/shared/form-errors.ts(export./form-errors): the error shapes, the issue-to-field mapping and the$fetcherror reader. No Vue and no DOM, so Nitro handlers import it.packages/nuxt-layer-ui/app/forms/(not auto-scanned;form-controller.tsis export./forms):form-values.ts(clone,deepEqual,getPath,setPath),form-controller.ts(createFormController, plain Vue reactivity with the announcer, focus andnextTickpassed in) andunsaved-changes.ts(createLeavePrompt, the leave decisions, no router).app/composables/useForm.tsanduseUnsavedChangesGuard.ts: thin Nuxt adapters over that code.
The blueprint’s useFormField and shared/types.ts weren’t needed: UiFormField reads the controller that UiForm provides.
import type { StandardSchemaV1 } from '@standard-schema/spec';
type In<S extends AnyFormSchema> = StandardSchemaV1.InferInput<S>;
type Out<S extends AnyFormSchema> = StandardSchemaV1.InferOutput<S>;
export type AnyFormSchema = StandardSchemaV1<Record<string, unknown>>;
export type FieldErrors = Record<string, string[]>; // dot paths
export type ServerFormError = { fieldErrors?: FieldErrors; formError?: string };
export type FormStatus = 'idle' | 'invalid' | 'pending' | 'saved' | 'failed';
export interface UseFormOptions<S extends AnyFormSchema> {
schema: S;
initialValues: In<S>;
id?: string; // id prefix: `${id}-${name}`; default useId()
validateOn?: { initial: 'blur' | 'submit'; afterError: 'change' }; // default { initial: 'submit', afterError: 'change' }
onSubmit(values: Out<S>, ctx: { signal: AbortSignal }): Promise<void> | void;
mapServerError?(error: unknown): ServerFormError | null; // default reads FetchError.data.data; null = handled elsewhere
announce?: { saving?: string; saved?: string } | false;
}
export interface FormController<S extends AnyFormSchema = AnyFormSchema> {
readonly id: string;
readonly values: Ref<In<S>>;
readonly errors: Readonly<Ref<FieldErrors>>;
readonly formError: Ref<string | null>;
readonly touched: Readonly<Ref<ReadonlySet<string>>>;
readonly dirty: ComputedRef<boolean>;
readonly pending: Readonly<Ref<boolean>>;
readonly status: Readonly<Ref<FormStatus>>;
readonly statusMessage: ComputedRef<string>; // "Saving…", the saved text while clean, else ''
readonly submitCount: Readonly<Ref<number>>;
readonly errorCount: ComputedRef<number>; // fields with an error, plus one for a form-level error
fieldId(name: string): string;
error(name: string): string | undefined;
field(name: string): FieldBinding;
handleSubmit(event?: Event): Promise<void>;
validate(name?: string): Promise<boolean>;
setErrors(errors: ServerFormError): void;
reset(values?: In<S>): void; // no argument: back to the last baseline
rebase(name: string, normalized: unknown): void;
focusFirstInvalid(): void;
abort(): void;
}
export interface FieldBinding {
id: string;
name: string;
modelValue: unknown;
'onUpdate:modelValue': (value: unknown) => void;
onBlur: () => void;
'aria-invalid'?: 'true';
'aria-describedby'?: string; // only when it points at something
'aria-labelledby'?: string; // added by UiFormField
'aria-required'?: 'true'; // added by UiFormField
}
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")
- UiForm renders
<form novalidate :aria-busy>and provides the controller to its parts. - UiFormField:
- the label is
forthe field id and has the id${fieldId}-label; hint${fieldId}-hint; error${fieldId}-error; - the error uses
--theme-error-ink-color, thecircle-alerticon and a visually hidden “Error:” prefix; - fields carry
data-field-name; - the slot is
{ field, invalid }.FieldBindinghas noinvalid: the kit rule “never pass a prop the component doesn’t declare” forbids it on controls without the prop.invalidis a separate boolean for the controls that declare it (UiInputText,UiTextarea,UiSelect); UiFormFieldaddsaria-labelledby(the label) as well aslabel[for], so controls that a label can’t name, such as PrimeVue’sUiSelectcombobox, are named too, and merges the hint id intoaria-describedby.
- the label is
- Failed submit: the summary lists links to each invalid field,
focusFirstInvalid()runs (the summary takes focus when the field isn’t on the page or there is only a form-level error), the announcer reads the error count, and fields switch to validating on change. - Pending: the submit button shows
loadingand the form hasaria-busy. Inputs stay enabled and resubmitting is ignored, including while an async schema validates. The announcer says “Saving…” and then the saved text, whichUiFormActionsalso shows. The saved text needs a clean form: the pagerebases each saved field orresets to the saved values. - Unsaved changes (owner Q3 B): route navigation opens an in-page
UiConfirmDialog(“Leave without saving?”, Stay focused first, Leave in danger), awaited by the router guard thatuseUnsavedChangesGuard(form.dirty, { allow, focusOnStay })registers on route leave and route update. Reload and close keep the browser’s ownbeforeunloadprompt, the only one browsers allow there. - Server errors:
packages/web-layer-admin/server/utils/validation-error.tsthrows a 422 with{ fieldErrors, formError }(validationError();adminPostWriteError()maps a failed blog write to 422 / 409 / 404 / 400).- A 409 slug conflict maps to
fieldErrors.slug(owner Q5 A), so the message sits on the Slug field and the summary links to it. A 404 or a 400 maps toformError. - The shared schema lives in
web-layer-admin/shared/blog-schema.ts. The admin form validates with it, andcore/web’sserver/api/posts/parse-body.tsparses create and update bodies with it (owner Q1 A).
4. Data and CRUD
export interface CrudAdapter<T, Id, F, C = Partial<T>, U = Partial<T>> {
getId(item: T): Id;
list(p: {
filter: F;
offset: number;
limit: number;
sort?: SortState;
signal: AbortSignal;
}): Promise<{ items: T[]; total?: number }>;
get?(id: Id): Promise<T>;
create?(input: C): Promise<T>;
update?(id: Id, patch: U): Promise<T>;
remove?(id: Id): Promise<void>;
}
export interface SortState {
field: string;
order: 'asc' | 'desc';
}
export function usePagedList<T>(o: {
fetchPage: (p: { offset: number; limit: number; signal: AbortSignal }) => Promise<{ items: T[]; total?: number }>;
pageSize?: number;
key: MaybeRefOrGetter<unknown>;
}): {
items: Ref<T[]>;
total: Ref<number | undefined>;
loading: Ref<boolean>;
error: Ref<unknown>;
hasMore: ComputedRef<boolean>;
loadMore(): Promise<void>;
reset(): void;
};
export function useConfirmUndo<T, Id>(o: {
getId(item: T): Id;
describe(item: T): string;
hide(item: T): void;
restore(item: T): void;
commit(item: T): Promise<void>;
delayMs?: number;
}): {
confirmingId: Ref<Id | null>;
request(item: T): void;
cancel(): void;
confirm(item: T): void;
undo(id: Id): void;
pending: Ref<Array<{ item: T; deadline: number; paused: boolean }>>;
pause(id: Id): void;
resume(id: Id): void;
flush(): Promise<void>;
};
export function useCrudResource<T, Id, F>(
adapter: CrudAdapter<T, Id, F>,
o: { filter: Ref<F>; pageSize?: number }
): ReturnType<typeof usePagedList<T>> & {
save(id: Id | null, input: Partial<T>): Promise<T>;
undoable: ReturnType<typeof useConfirmUndo<T, Id>>;
selected: Ref<T | null>;
};
export function useRouteQueryState<S extends object>(
codec: { keys: readonly string[]; read(q: LocationQuery, d: S): S; write(s: S, d: S): LocationQuery },
defaults: S
): ToRefs<S> & { filtered: ComputedRef<boolean>; clear(): void };
// useBrowseQuery becomes useRouteQueryState(browseCodec, defaults), keeping the same behaviour
- Load more: announces “Loaded 24 more, 72 of 120”; focus stays on the button.
- Undo window: the 8-second window pauses while Undo is hovered or focused (WCAG 2.2.1), and each line says so in a hint that Undo’s
aria-describedbyalso reads.- Before swapping, check the current commit-on-leave versus cancel-on-leave behaviour in the media page and
AppStyleStudio.
- Before swapping, check the current commit-on-leave versus cancel-on-leave behaviour in the media page and
- UiConfirmInline: “Delete X? [Delete] [Cancel]” in place. Focus goes to Cancel, and Escape cancels.
- UiUndoNotice: a polite status line, “Deleted X. [Undo]”.
UiDataTable wraps PrimeVue DataTable and Column:
export interface UiDataTableColumn<T> {
field: string;
header: string;
sortable?: boolean;
align?: 'start' | 'end';
format?(value: unknown, row: T): string;
priority?: 1 | 2 | 3;
headerHidden?: boolean;
}
export interface UiDataTableProps<T> {
rows: T[];
columns: UiDataTableColumn<T>[];
rowKey: string | ((r: T) => string);
caption: string;
captionHidden?: boolean;
loading?: boolean;
emptyMessage?: string;
selectionMode?: 'single' | 'multiple';
paginator?: { rows: number; totalRecords?: number } | false;
lazy?: boolean;
}
// v-model:sort / selection / page; emits rowActivate; slots cell-<field>, actions, empty, toolbar
- Responsive: a container query switches to stacked rows below about 32em. Otherwise the table sits in a scroll region (
role="region",tabindex="0",aria-label). - Sorting:
aria-sort, plus a polite “Sorted by …” announcement. - PrimeVue includes: add DataTable, Column, ColumnGroup, Row, Paginator, Chart, Drawer and Toolbar to the components list in
tgmcPrimeVueConfig().
UiChart wraps PrimeVue Chart (Chart.js):
export type ChartTone = 'primary' | 'secondary' | 'accent' | 'success' | 'warning' | 'error' | 'info' | 'neutral';
export interface UiChartProps {
type: 'bar' | 'line' | 'pie' | 'doughnut';
title: string;
summary: string;
labels: string[];
series: Array<{ label: string; data: number[]; tone?: ChartTone }>;
valueFormat?(n: number): string;
table?: 'toggle' | 'visible';
height?: string;
}
- Colours:
useChartTheme()maps tones to--theme-<tone>-color, text to--theme-text-colorand grid lines to--theme-border-color.- Values are read with
getComputedStyleand normalized through a 1×1 canvas, because they can becolor-mix(). - Colours are re-resolved on theme or mode change (a MutationObserver on
<html>plusprefers-color-scheme). - There are no colour literals in code.
- Values are read with
- Accessibility:
- The canvas gets
role="img"and anaria-labelof title plus summary. - A “Show data table” disclosure (
aria-expanded) renders UiDataTable in native mode. - Series are told apart by point style or dash pattern, not colour alone.
- Animation is off under reduced motion.
- Tick font size is at least
--type-min.
- The canvas gets
- SSR:
<ClientOnly>, with the table as the fallback.
UiCrudView:
export interface UiCrudViewProps<T, Id, F> {
resource: ReturnType<typeof useCrudResource<T, Id, F>>;
title: string;
columns: UiDataTableColumn<T>[];
itemLabel(row: T): string;
filters?: Array<{
key: keyof F & string;
label: string;
type: 'chips' | 'select' | 'search';
options?: { value: string; label: string }[];
}>;
editor?: 'drawer' | 'page';
canCreate?: boolean;
canEdit?: boolean;
canDelete?: boolean;
}
// v-model:view ('table'|'grid'); slots toolbar, summary (UiChart), cell-<field>, grid-item, editor({ item, close }), empty
- Layout order:
- Header (title and Create).
- Filter bar (chips with
aria-pressed, synced to the route query). - Status line (“Showing 24 of 120”).
- Table or grid.
- Load more.
- UiDrawer editor.
- Undo region.
- UiDrawer: built on native
<dialog>withshowModal()(built-in inert background and focus containment), plususeFocusTrapas a safety net.- It could retire both
inertOutsidecopies; check this against why the custom trap exists.
- It could retire both
5. UiRichTextEditor (Tiptap v3)
export interface UiRichTextEditorProps {
modelValue?: string;
id?: string;
label?: string;
ariaDescribedby?: string;
invalid?: boolean;
placeholder?: string;
maxLength?: number;
headingLevels?: Array<2 | 3 | 4>;
sourceToggle?: boolean;
}
// emits update:modelValue(md), normalized(md) → form.rebase, blur; expose focus()
- Extensions:
StarterKit, with no Tab binding.Link, limited to http, https and mailto, withisAllowedUri.PlaceholderandCharacterCount(from@tiptap/extensions).@tiptap/markdown(verify the version, or fall back totiptap-markdown).- Images and tables are phase 2.
- Markdown in and out:
- Load with
setContent(md, { contentType: 'markdown' }); read back withgetMarkdown(). - Debounce updates by 150ms and flush on blur.
- Skip
setContentwhen the incoming value equals the last emitted one. - Emit
normalizedafter the first load.
- Load with
- Sanitisation:
- The schema drops unknown nodes and raw HTML is off.
- Pasted HTML is stripped (
transformPastedHTML). app/utils/markdown-policy.tslists the allowed nodes, marks and protocols; a test asserts parity with thesanitize-htmlrender config.- The server keeps sanitising at render time and enforces a maximum length.
- SSR: Tiptap is loaded with
await import('./create-editor')inonMounted, inside<ClientOnly>. The#fallbackis aUiTextarea, which also serves no-JS and source mode. - Toolbar accessibility:
role="toolbar",aria-label="Formatting"andaria-controls.- Roving tabindex with Left/Right/Home/End.
- Toggle buttons carry
aria-pressedandaria-keyshortcuts. - The heading picker is a
UiSelect. - Links are added through a small dialog form, never
window.prompt. - Buttons are at least 44px and the toolbar wraps at 375px.
- Content area:
role="textbox",aria-multiline,aria-labelledby,aria-describedbyandaria-invalid.- The focus ring sits on the wrapper’s
:focus-within. - Tab always leaves the editor. List indent uses a toolbar button and
Ctrl+]/Ctrl+[. - The character count is announced at 90% and 100%.
- Icons: bold, italic, strikethrough, code, square-code, list, list-ordered, quote, link, unlink, minus, undo-2, redo-2, indent-increase, indent-decrease, circle-alert.
6. UiMultiUpload
export type UploadStatus =
'queued' | 'uploading' | 'processing' | 'done' | 'error' | 'canceled' | 'conflict' | 'rejected';
export interface UploadItem<R = unknown> {
id: string;
file: File;
name: string;
status: UploadStatus;
progress: number | null;
error?: string;
conflict?: { suggestedName: string | null; message: string };
result?: R;
attempts: number;
}
export class UploadConflictError extends Error {
constructor(
readonly suggestedName: string | null,
msg: string
) {
super(msg);
}
}
export interface UploaderAdapter<R> {
readonly reportsProgress: boolean;
readonly maxBytes?: number;
upload(
file: File,
ctx: { name: string; signal: AbortSignal; onProgress(loaded: number, total: number): void }
): Promise<R>;
}
export interface UploadRules {
accept?: string[];
maxBytes?: number;
maxFiles?: number;
allowEmpty?: boolean;
}
export type ConflictDecision = { action: 'rename'; name: string } | { action: 'skip' };
export function useUploadQueue<R>(o: {
adapter: UploaderAdapter<R>;
rules?: UploadRules;
concurrency?: number;
onConflict?(item: UploadItem<R>): Promise<ConflictDecision>;
}): {
items: Ref<UploadItem<R>[]>;
add(files: FileList | File[]): void;
cancel(id: string): void;
cancelAll(): void;
retry(id: string): void;
retryFailed(): void;
remove(id: string): void;
active: ComputedRef<boolean>;
summary: ComputedRef<{ done: number; failed: number; total: number }>;
};
- Adapters live in
packages/media-client/src/upload-adapters.ts, behind a new browser-only./browserexport.createBase64Uploader: today’s behaviour; FileReader progress, thenuploadBase64. Concurrency 1, and a conservativemaxBytes.createPresignedUploader:createPresign; a 409 becomesUploadConflictError.- An XHR PUT with the signed headers, using
upload.onprogressand abort on the signal. completeIngest.
It re-presigns once the URL has expired. Prerequisite: MinIO and S3 CORS must allow PUT from the admin origin.
- Validation: MIME type and extension, size, count, empty files and duplicates. Rejected files stay visible as rows with a reason.
- Queue: a scheduler fills free slots in order (default concurrency 2). Cancel works per row and for all; retry is per row or “Retry failed”.
- Conflict: an inline row prompt, “Use
" / "Rename…" / "Skip". There is no replace option. - Input:
- The drop zone is a
<label>for a visually hidden, focusable<input type="file" multiple :accept>. - Drag-and-drop is an enhancement only.
- Targets are at least 44px, and long names use
overflow-wrap: anywhere.
- The drop zone is a
- Status:
- Each row has a
<progress>with a name, plus visible percentage text; row actions are named. - A global
role="status"reads “Uploading N of M”. - The announcer speaks only at start, completion or failure, and the end, never on progress ticks.
- A
beforeunloadwarning is active while uploads are running.
- Each row has a
- Emits:
uploaded,complete,rejected; optionalv-model:items.
7. Duplicates to consolidate
- the two
inertOutsidecopies and admin’sfocus-trap— done: one copy in@tgmc/nuxt-layer-base; useMatchMedia(admin) andusePrefersReducedMotion(web) — done: one copy each in@tgmc/nuxt-layer-base;- the two delete+Undo state machines (media page,
AppStyleStudio); iconConfigduplicated in bothnuxt.config.tsfiles;- three Sass
additionalDatafunctions; - admin importing
../web/config-properties/primevue-prop— done: the config lives in@tgmc/nuxt-layer-ui(src/config/primevue.ts); - the local
.sr-onlyversus the theme’s utility; - ad-hoc live regions versus
UiAnnouncer; media-pagingversususePagedList;useBrowseQueryversususeRouteQueryState.
8. Defects to fix in the nuxt-layer-base draft (Task 4)
useA11yAnnounceruses module-level refs, which leak between SSR requests. UseuseState('tgmc:a11y:polite' | 'tgmc:a11y:assertive'), run timers only on the client, and clear any pending timer.role="status"combined with a dynamicaria-live="assertive"contradicts itself. Render two always-present regions, onerole="status"and onerole="alert", mounted once with an instance guard.- UiSkipLink:
- Its colour literals (
#ffffff,#111827,#0284c7,rgba(...)) failcolors-scss. top: -9999pxfails the units policy.outline: noneplus a shadow-only focus state disappears in forced-colors mode.
Fix: theme roles, the
focus-ring-shadowmixin,min-height: var(--touch-target)andtransform: translateY(-120%). The target<main id>needstabindex="-1"; check for an existing skip link inlayouts/site.vue. - Its colour literals (
- Templates aren’t Pug. Use the theme’s visually-hidden utility (check its name in
theme/core/scss/globals). - The
../../theme/corepath works only inside the monorepo. Usepkg:orcreateRequire. additionalDatacollides with the apps’ own (the app’s function wins), and it lacks thenode_modulesandnuxt-autoguards. Make the layer the single owner viatgmcScssAdditionalData(extra).@nuxt/icon ^1.10.3installs a nested v1. Align to^2.5.1, pin@nuxt/a11yto root’s resolved version, setnuxt ^4.5, and add@iconify-json/lucide.- The icon config has no
clientBundle. Move the list intosrc/config/icons.tsand retarget the test. - Auto-imports:
imports.importsdoesn’t cover server routes (that needsnitro.imports).imports.dirs: ['app/composables']probably resolves toapp/app/composables(verify); drop it.- Prefer explicit imports over generic names (
isObject,deepMerge), and verify they exist in@tgmc/utilities/universal.
- The head
metaduplicates Nuxt’s defaults; useapp.head.charset/viewport.htmlAttrs.langconflicts with@nuxtjs/i18n, so leave it to the app. - The a11y config fails on violations and writes its report in every environment, and
rules: []does nothing. Scope it:$developmentfor highlights and logging,$testfor the report with fail-on-violation,$productiondisabled. - Missing plumbing: Nx targets,
tsconfig.json,eslint.config.js, Prettier Pug config,vitest.config.ts, and anuxt preparestep for types. - Name collisions: register under
app/components/a11ywithpathPrefix: falseand check that noUi*names are duplicated. - Announcer race: the 50ms clear-then-set loses back-to-back messages. Queue messages or use
{ id, text }, and clear the timer on each call.