An app drawn with MUI
Draw a Surfaces UI app document with MUI (Material UI) instead of this library's components: MUI's app bar, cards, text fields, selects, buttons, alerts and dialog. The app here was written by a live model from the MUI catalog's own prompt, and runs operations against a backend that asks a person to approve a change that cannot be undone. No module of @surfaces-ui/components or @surfaces-ui/spec is installed or bundled.
The catalog says what each MUI component takes, in words an agent reads and in Zod props every document is checked against:
catalog.ts:
// A catalog for MUI (Material UI): what an agent is told, and what every document is checked against.
// Written by the team that uses MUI; nothing here is from Surfaces UI's own components.
import { action, childList, dataBinding, defineCatalog, dynamicString } from "@surfaces-ui/document";
import { z } from "zod";
export const muiCatalog = defineCatalog({
id: "urn:example:mui:v1",
title: "MUI",
description: "Material UI components: layout, cards, text, text fields, selects, buttons, links and alerts.",
components: {
Stack: {
description: "Lays its children out in a column (or a row, with direction row), with even space between them.",
props: { children: childList, direction: z.enum(["column", "row"]).optional() },
example: { id: "root", component: "Stack", children: ["title", "card"] },
},
Card: {
description: "A raised card that groups related things, with an optional title.",
props: { title: dynamicString.optional(), children: childList },
example: { id: "card", component: "Card", title: "Add a note", children: ["order"] },
},
Heading: {
description: "A heading. level 1 is the page's title, used once per page; level 2 heads a part of it.",
props: { text: dynamicString, level: z.union([z.literal(1), z.literal(2)]).optional() },
example: { id: "title", component: "Heading", text: "Orders", level: 1 },
},
Text: {
description: "A paragraph of text. secondary is quieter, for help.",
props: { text: dynamicString, tone: z.enum(["primary", "secondary"]).optional() },
example: { id: "intro", component: "Text", text: "Type an order number.", tone: "secondary" },
},
TextField: {
description: "A labelled text box (multiline for longer text). What the person types is written to `value`. When an operation refuses the value, the server's words are shown under it.",
props: { label: z.string(), value: dataBinding, multiline: z.boolean().optional(), helperText: z.string().optional(), required: z.boolean().optional() },
example: { id: "order", component: "TextField", label: "Order number", value: { "@path": "/app/orderId" }, required: true },
},
Select: {
description: "A labelled drop-down of fixed options. The chosen option's value is written to `value`.",
props: { label: z.string(), value: dataBinding, options: z.array(z.object({ value: z.string(), label: z.string() })).min(1) },
example: { id: "kind", component: "Select", label: "Kind", value: { "@path": "/kind" }, options: [{ value: "call", label: "Call back" }, { value: "other", label: "Other" }] },
},
Button: {
description: "A button. Its action is a function such as `navigate`, `setValue` or `run` (an operation). contained is the main action of a card; color error for an action that removes something. While its operation runs it says so, and a refusal is shown under it.",
props: { label: z.string(), action, variant: z.enum(["contained", "outlined", "text"]).optional(), color: z.enum(["primary", "error"]).optional() },
events: { press: { description: "When pressed. Carries only the context declared in the action." } },
example: { id: "go", component: "Button", label: "Help", variant: "outlined", action: { functionCall: { "@call": "navigate", args: { to: "/help" } } } },
},
Link: {
description: "A link to another route of the app.",
props: { text: dynamicString, to: z.string().startsWith("/") },
example: { id: "back", component: "Link", text: "Back to notes", to: "/" },
},
Alert: {
description: "A short message in a coloured box: info for guidance, warning before something that cannot be undone.",
props: { text: dynamicString, severity: z.enum(["info", "success", "warning", "error"]).optional() },
example: { id: "warn", component: "Alert", severity: "warning", text: "Clearing a flag cannot be undone." },
},
Divider: {
description: "A thin line between two parts of a page.",
props: {},
example: { id: "line", component: "Divider" },
},
},
});A renderer per component returns MUI. Three of them draw what an operation's server said, because the runtime draws nothing of its own: Press shows a refusal as an alert under the button and says "…" while the run is out (useRunState), Field shows the server's words under the value it refused and takes focus (useRunFieldError), and useMuiConfirm asks for approval in MUI's Dialog, with a reason where the operation needs one and "confirm" typed for one that cannot be undone. The app's navigation is MUI's AppBar, and a document's theme request becomes MUI's theme (MuiTheme):
renderers.tsx:
// MUI renderers for the catalog, the app's navigation as an MUI app bar, the theme request mapped onto an MUI
// theme, and an approval dialog drawn with MUI's Dialog. The runtime draws none of these: each is a slot.
import Alert from "@mui/material/Alert";
import AppBar from "@mui/material/AppBar";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
import Divider from "@mui/material/Divider";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import MuiLink from "@mui/material/Link";
import MenuItem from "@mui/material/MenuItem";
import MuiSelect from "@mui/material/Select";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import { ThemeProvider, createTheme, useTheme } from "@mui/material/styles";
import { type AppNavProps, type ComponentRenderer, RUN_RISK, type RunAnswer, type RunApproval, type ThemeScopeProps, useAppLinks, useRunFieldError, useRunState } from "@surfaces-ui/runtime";
import { useEffect, useId, useMemo, useRef, useState } from "react";
const words = (value: unknown) => (value == null ? "" : String(value));
const pathOf = (value: unknown) => (value && typeof value === "object" && "@path" in value ? String((value as { "@path": unknown })["@path"]) : undefined);
function Field({ id, label, value, path, multiline, helperText, required, change }: { id: string; label: string; value: string; path?: string; multiline?: boolean; helperText?: string; required?: boolean; change(value: string): void }) {
const refused = useRunFieldError(path);
const input = useRef<HTMLInputElement>(null);
useEffect(() => {
if (refused.first) input.current?.focus();
}, [refused.first, refused.at]);
return (
<TextField
id={`f-${id}`}
inputRef={input}
label={label}
value={value}
onChange={(event) => change(event.target.value)}
multiline={multiline}
minRows={multiline ? 3 : undefined}
required={required}
error={!!refused.message}
helperText={refused.message ?? helperText}
fullWidth
/>
);
}
function Choice({ label, value, options, change }: { label: string; value: string; options: { value: string; label: string }[]; change(value: string): void }) {
const id = useId();
return (
<FormControl fullWidth>
<InputLabel id={id}>{label}</InputLabel>
<MuiSelect labelId={id} label={label} value={options.some((o) => o.value === value) ? value : ""} onChange={(event) => change(String(event.target.value))}>
{options.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</MuiSelect>
</FormControl>
);
}
function Press({ id, label, variant, color, press }: { id: string; label: string; variant?: "contained" | "outlined" | "text"; color?: "primary" | "error"; press(): void }) {
const { state, reread } = useRunState(id);
const working = state?.status === "running" || state?.status === "approving";
const refused = state && ["invalid", "refused", "stale", "failed"].includes(state.status);
return (
<Stack spacing={1} sx={{ alignItems: "flex-start" }}>
<Button variant={variant ?? "contained"} color={color ?? "primary"} aria-disabled={working || undefined} onClick={working ? undefined : press} sx={{ minHeight: 44 }}>
{working ? `${label}…` : label}
</Button>
{refused && (
<Alert severity="error" role="alert" sx={{ width: "100%" }}>
{state.message}
</Alert>
)}
{reread && (
<Button variant="text" onClick={reread}>
Read again
</Button>
)}
</Stack>
);
}
function AppLink({ text, to }: { text: string; to: string }) {
const links = useAppLinks();
return (
<MuiLink
href={links ? links.href(to) : to}
onClick={(event) => {
if (!links || event.metaKey || event.ctrlKey) return;
event.preventDefault();
links.go(to);
}}
>
{text}
</MuiLink>
);
}
function Heading({ text, level }: { text: string; level: 1 | 2 }) {
return (
<Typography variant={level === 1 ? "h4" : "h6"} component={level === 1 ? "h1" : "h2"}>
{text}
</Typography>
);
}
export const muiRenderers: Record<string, ComponentRenderer> = {
Stack: ({ props, component, children }) => (
<Stack direction={props.direction === "row" ? { xs: "column", sm: "row" } : "column"} spacing={2}>
{children(component.children)}
</Stack>
),
Card: ({ props, component, children }) => (
<Card variant="outlined">
<CardContent>
<Stack spacing={2}>
{props.title ? <Heading text={words(props.title)} level={2} /> : null}
{children(component.children)}
</Stack>
</CardContent>
</Card>
),
Heading: ({ props }) => <Heading text={words(props.text)} level={props.level === 2 ? 2 : 1} />,
Text: ({ props }) => (
<Typography color={props.tone === "secondary" ? "text.secondary" : "text.primary"}>{words(props.text)}</Typography>
),
TextField: ({ props, component, setData }) => (
<Field id={component.id} label={words(props.label)} value={words(props.value)} path={pathOf(component.value)} multiline={props.multiline === true} helperText={props.helperText as string | undefined} required={props.required === true} change={(value) => setData(component.value, value)} />
),
Select: ({ props, component, setData }) => <Choice label={words(props.label)} value={words(props.value)} options={props.options as { value: string; label: string }[]} change={(value) => setData(component.value, value)} />,
Button: ({ props, component, dispatch }) => <Press id={component.id} label={words(props.label)} variant={props.variant as "contained"} color={props.color as "primary"} press={() => dispatch(component.action)} />,
Link: ({ props }) => <AppLink text={words(props.text)} to={words(props.to)} />,
Alert: ({ props }) => <Alert severity={(props.severity as "info") ?? "info"}>{words(props.text)}</Alert>,
Divider: () => <Divider />,
};
/** The app's navigation as an MUI app bar of links, the current one marked. */
export function muiNav({ title, items, go }: AppNavProps) {
return (
<AppBar position="static" color="primary" elevation={0}>
<Toolbar component="nav" aria-label={title} sx={{ gap: 1, flexWrap: "wrap", py: 1 }}>
<Typography component="p" variant="h6" sx={{ mr: 2 }}>
{title}
</Typography>
{items.map((item) => (
<Button
key={item.to}
href={item.href}
color="inherit"
aria-current={item.current ? "page" : undefined}
variant={item.current ? "outlined" : "text"}
onClick={(event) => {
event.preventDefault();
go(item.to);
}}
sx={{ minHeight: 44 }}
>
{item.label}
</Button>
))}
</Toolbar>
</AppBar>
);
}
/** A document's theme request onto MUI's theme: its accent becomes the primary colour, its radius the shape. */
export function MuiTheme({ request, children }: ThemeScopeProps) {
const outer = useTheme();
const theme = useMemo(() => createTheme(outer, { ...(request.accent ? { palette: { primary: { main: request.accent } } } : {}), ...(request.radius !== undefined ? { shape: { borderRadius: request.radius } } : {}) }), [outer, request.accent, request.radius]);
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
/** Asks a person to approve an operation with MUI's Dialog. An irreversible one is allowed only once they type "confirm". */
export function useMuiConfirm() {
const [asked, setAsked] = useState<{ request: RunApproval; answer(answer: RunAnswer | undefined): void } | undefined>();
const [reason, setReason] = useState("");
const [typed, setTyped] = useState("");
const confirm = (request: RunApproval) =>
new Promise<RunAnswer | undefined>((resolve) => {
setReason("");
setTyped("");
setAsked({ request, answer: (answer) => (setAsked(undefined), resolve(answer)) });
});
const request = asked?.request;
const irreversible = request?.risk === RUN_RISK.irreversible;
const ready = !!request && (!request.reasonRequired || reason.trim() !== "") && (!irreversible || typed.trim().toLowerCase() === "confirm");
const dialog = (
<Dialog open={!!asked} onClose={() => asked?.answer(undefined)} aria-labelledby="approve-title" aria-describedby="approve-detail">
{request && (
<>
<DialogTitle id="approve-title">{request.title}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 1 }}>
<DialogContentText id="approve-detail">{request.detail}</DialogContentText>
{irreversible && <Alert severity="warning">This cannot be undone.</Alert>}
{request.reasonRequired && <TextField label="Reason" required value={reason} onChange={(event) => setReason(event.target.value)} multiline minRows={2} />}
{irreversible && <TextField label='Type "confirm" to allow it' value={typed} onChange={(event) => setTyped(event.target.value)} />}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={() => asked!.answer(undefined)}>Cancel</Button>
<Button onClick={() => asked!.answer({ allow: false, reason })}>Don't allow</Button>
<Button variant="contained" color={irreversible ? "error" : "primary"} aria-disabled={!ready || undefined} onClick={ready ? () => asked!.answer({ allow: true, reason }) : undefined}>
Allow
</Button>
</DialogActions>
</>
)}
</Dialog>
);
return { confirm, dialog };
}The app is one document with no code: three pages, an order number shared between them and kept in the address, a note added with run, and a flag cleared with an operation that cannot be undone:
app.ts:
import type { AppDocument } from "@surfaces-ui/document";
/**
* The app, as a live model wrote it against the MUI catalog (with `appAgentPrompt` and the desk's operations): three
* pages, an order number shared between them and kept in the address, a note added with `run`, and a flag cleared
* with an operation that cannot be undone. It holds no code and names no MUI component the catalog does not have.
*/
export const deskApp: AppDocument = {
"id": "support-desk",
"title": "Support desk",
"catalogId": "urn:example:mui:v1",
"state": {
"orderId": {
"type": "string",
"default": "",
"keep": "url"
}
},
"nav": [
{
"label": "Add a note",
"to": "/"
},
{
"label": "Review flags",
"to": "/flags"
},
{
"label": "Help",
"to": "/help"
}
],
"operations": [
"add-order-note",
"clear-flag"
],
"pages": [
{
"route": "/",
"page": {
"id": "home",
"title": "Add a note",
"catalogId": "urn:example:mui:v1",
"components": [
{
"id": "root",
"component": "Stack",
"children": [
"title",
"intro",
"card"
]
},
{
"id": "title",
"component": "Heading",
"text": "Add a note to an order",
"level": 1
},
{
"id": "intro",
"component": "Text",
"text": "Type the order number, choose the kind of note and write it. The note is saved starting with its kind, like [Refund].",
"tone": "secondary"
},
{
"id": "card",
"component": "Card",
"title": "New note",
"children": [
"order",
"kind",
"note",
"preview",
"add"
]
},
{
"id": "order",
"component": "TextField",
"label": "Order number",
"value": {
"@path": "/app/orderId"
},
"required": true
},
{
"id": "kind",
"component": "Select",
"label": "Kind of note",
"value": {
"@path": "/kind"
},
"options": [
{
"value": "Call back",
"label": "Call back"
},
{
"value": "Refund",
"label": "Refund"
},
{
"value": "Complaint",
"label": "Complaint"
}
]
},
{
"id": "note",
"component": "TextField",
"label": "Note",
"value": {
"@path": "/noteText"
},
"multiline": true,
"required": true
},
{
"id": "preview",
"component": "Text",
"tone": "secondary",
"text": {
"@call": "formatString",
"args": {
"value": "Will be saved as: [${/kind|Call back}] ${/noteText|(no text yet)}"
}
}
},
{
"id": "add",
"component": "Button",
"label": "Add note",
"variant": "contained",
"action": {
"functionCall": {
"@call": "run",
"args": {
"operation": "add-order-note",
"args": {
"order_id": {
"@path": "/app/orderId"
},
"note": {
"@call": "formatString",
"args": {
"value": "[${/kind|Call back}] ${/noteText}"
}
}
},
"then": {
"@call": "setValue",
"args": {
"path": "/noteText",
"value": ""
}
}
}
}
}
}
],
"data": {
"kind": "Call back",
"noteText": ""
},
"a2ui": "1.0"
}
},
{
"route": "/flags",
"page": {
"id": "flags",
"title": "Review flags",
"catalogId": "urn:example:mui:v1",
"components": [
{
"id": "root",
"component": "Stack",
"children": [
"title",
"intro",
"card"
]
},
{
"id": "title",
"component": "Heading",
"text": "Review flags",
"level": 1
},
{
"id": "intro",
"component": "Text",
"text": "Clear the review flag on one order.",
"tone": "secondary"
},
{
"id": "card",
"component": "Card",
"title": "Clear an order's flag",
"children": [
"order",
"warn",
"clear"
]
},
{
"id": "order",
"component": "TextField",
"label": "Order number",
"value": {
"@path": "/app/orderId"
},
"required": true
},
{
"id": "warn",
"component": "Alert",
"severity": "warning",
"text": "Clearing a flag removes it for good. It cannot be undone."
},
{
"id": "clear",
"component": "Button",
"label": "Clear flag",
"variant": "contained",
"color": "error",
"action": {
"functionCall": {
"@call": "run",
"args": {
"operation": "clear-flag",
"args": {
"order_id": {
"@path": "/app/orderId"
}
}
}
}
}
}
],
"a2ui": "1.0"
}
},
{
"route": "/help",
"page": {
"id": "help",
"title": "Help",
"catalogId": "urn:example:mui:v1",
"components": [
{
"id": "root",
"component": "Stack",
"children": [
"title",
"p1",
"p2",
"p3",
"p4",
"back"
]
},
{
"id": "title",
"component": "Heading",
"text": "About the support desk",
"level": 1
},
{
"id": "p1",
"component": "Text",
"text": "Add a note: type an order number, choose the kind of note (Call back, Refund or Complaint) and write it. The note is saved on the order starting with its kind in square brackets, for example \"[Refund] Customer asked for money back\". After it is saved, the note box is emptied so you can write the next one."
},
{
"id": "p2",
"component": "Text",
"text": "Review flags: clear the review flag on the same order. This removes the flag for good."
},
{
"id": "p3",
"component": "Text",
"text": "The order number stays the same when you move between pages, and it is in the page address, so a link you share opens on the same order."
},
{
"id": "p4",
"component": "Text",
"text": "Notes are signed with the name of whoever is signed in.",
"tone": "secondary"
},
{
"id": "back",
"component": "Link",
"text": "Back to adding a note",
"to": "/"
}
],
"a2ui": "1.0"
}
}
],
"a2ui": "1.0"
};The backend. Here it is in memory (memoryOperations), which behaves exactly as a server does; on your own backend each operation is your handler, reached over HTTP as in own-operations:
desk.ts:
import { type OperationActor, OperationError, type OperationSpec, memoryOperations } from "@surfaces-ui/data";
/** One order of the desk: whether it is flagged for review, and the notes written on it. */
export interface DeskOrder {
id: string;
flagged: boolean;
notes: { by: string; note: string }[];
}
/**
* The desk's backend, in memory: the two operations the app runs. On your own backend these are your handlers;
* `memoryOperations` checks the arguments, asks for approval where the operation needs it and records each run.
*/
export function supportDesk(actor: OperationActor = { id: "u-ana", name: "Ana Ruiz" }) {
const orders = new Map<string, DeskOrder>(["1001", "1002", "1003", "1004"].map((id) => [id, { id, flagged: id !== "1004", notes: [] }]));
const find = (id: unknown) => {
const order = orders.get(String(id).trim());
if (!order) throw new OperationError(`There is no order ${String(id)}.`);
return order;
};
const specs: OperationSpec[] = [
{
id: "add-order-note",
title: "Add order note",
description: "Adds a note to one order, signed with the name of whoever adds it.",
effect: "create",
target: "desk.notes",
args: [
{ name: "order_id", label: "Order", type: "text", required: true, pattern: "\\s*\\d+\\s*" },
{ name: "note", label: "Note", type: "longtext", required: true, maxLength: 500 },
],
run: (args) => {
const order = find(args.order_id);
order.notes.push({ by: actor.name, note: String(args.note) });
return { affected: 1, message: `Note added to order ${order.id}.` };
},
},
{
id: "clear-flag",
title: "Clear flag",
description: "Removes the review flag from one order, for good.",
effect: "delete",
target: "desk.flags",
risk: "irreversible",
reasonRequired: true,
args: [{ name: "order_id", label: "Order", type: "text", required: true }],
run: (args) => {
const order = find(args.order_id);
if (!order.flagged) throw new OperationError(`Order ${order.id} is not flagged.`);
order.flagged = false;
return { affected: 1, message: `Cleared the flag on order ${order.id}.` };
},
},
];
return { operations: memoryOperations({ operations: specs, actor: () => actor }), orders };
}The shell: MUI's theme, validateApp with the backend's operations before anything is drawn, and AppView with MUI in every slot. In dark mode MUI's error red is lightened, since its default reads at 3.7:1 on MUI's dark paper:
App.tsx:
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import { validateApp } from "@surfaces-ui/document";
import type { OperationDefinition } from "@surfaces-ui/proto";
import { AppView, type AppViewProps, type RunOperations, useHashLocation } from "@surfaces-ui/runtime";
import { useMemo } from "react";
import { deskApp } from "./app.js";
import { muiCatalog } from "./catalog.js";
import { MuiTheme, muiNav, muiRenderers, useMuiConfirm } from "./renderers.js";
export interface DeskProps {
/** Your backend's operations, and their definitions as it lists them. */
operations: RunOperations;
operationDefinitions: readonly OperationDefinition[];
/** What an approval is bound to, as your backend computes it (`approvalDigest` from `@surfaces-ui/data`). */
digest: AppViewProps["digest"];
mode?: "light" | "dark";
}
/** The whole app: one document drawn with MUI, the approval asked in MUI's Dialog, the address kept in the hash. */
export function App({ operations, operationDefinitions, digest, mode = "light" }: DeskProps) {
const location = useHashLocation();
const { confirm, dialog } = useMuiConfirm();
// A dark palette's error red is lightened so its text reads at 4.5:1 on MUI's dark paper.
const theme = useMemo(() => createTheme({ palette: { mode, primary: { main: mode === "dark" ? "#7fcfb0" : "#0b5d43" }, ...(mode === "dark" ? { error: { main: "#ef9a9a" } } : {}) } }), [mode]);
const problems = validateApp(deskApp, muiCatalog, { operations: operationDefinitions });
if (problems.length > 0) return <pre role="alert">{problems.map((p) => `${p.path}: ${p.message}`).join("\n")}</pre>;
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<style>{".mui-desk main { max-width: 760px; margin: 0 auto; padding: 24px 16px; }"}</style>
<AppView
app={deskApp}
catalog={muiCatalog}
renderers={muiRenderers}
nav={muiNav}
themeScope={MuiTheme}
operations={operations}
operationDefinitions={operationDefinitions}
confirm={confirm}
digest={digest}
className="mui-desk"
{...location}
/>
{dialog}
</ThemeProvider>
);
}The test adds a note through MUI's fields, has the server refuse an order number at its field, clears a flag through MUI's dialog (allowed only with a reason and "confirm" typed), and bundles the shell to list what is in it: of this repository's packages only document, runtime and trace, with MUI and no module of components, icons or spec:
mui-components.test.tsx:
// @vitest-environment jsdom
import path from "node:path";
import { approvalDigest } from "@surfaces-ui/data";
import { appAgentPrompt, validateApp } from "@surfaces-ui/document";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { build } from "vite";
import { afterEach, describe, expect, it } from "vitest";
import { App } from "./App.js";
import { deskApp } from "./app.js";
import { muiCatalog } from "./catalog.js";
import { supportDesk } from "./desk.js";
afterEach(() => {
cleanup();
window.location.hash = "";
});
async function open() {
const desk = supportDesk();
const { operations: definitions } = await desk.operations.listOperations({});
render(<App operations={desk.operations} operationDefinitions={definitions} digest={approvalDigest} />);
await screen.findByRole("heading", { name: "Add a note to an order" });
return { desk, definitions };
}
const live = () => document.querySelector(".sf-app-live")!.textContent!.trim();
describe("an app drawn with MUI", () => {
it("passes validateApp against the MUI catalog and the desk's operations", async () => {
const { operations } = await supportDesk().operations.listOperations({});
expect(validateApp(deskApp, muiCatalog, { operations })).toEqual([]);
const wrong = structuredClone(deskApp);
((wrong.pages[0] as { page: { components: { component: string }[] } }).page.components[1]!).component = "DataGrid";
expect(validateApp(wrong, muiCatalog).map((p) => p.message).join(" ")).toMatch(/DataGrid/);
// The prompt the app was written from names MUI's components and the desk's operations, and nothing of ours.
const prompt = appAgentPrompt(muiCatalog, { operations });
expect(prompt).toContain("add-order-note");
expect(prompt).not.toMatch(/DataGrid|FilterBar/);
});
it("adds a note from MUI's text fields and button, and shows a refusal at the field the server named", async () => {
const { desk } = await open();
expect(screen.getByRole("navigation", { name: "Support desk" })).toBeTruthy();
fireEvent.change(screen.getByRole("textbox", { name: /Order number/ }), { target: { value: "1002" } });
fireEvent.change(screen.getByRole("textbox", { name: /^Note/ }), { target: { value: "Customer will call back after five." } });
// The order number is app state kept in the address, so a link opens on the same order.
await waitFor(() => expect(window.location.hash).toContain("orderId=1002"));
fireEvent.click(screen.getByRole("button", { name: "Add note" }));
await waitFor(() => expect(live()).toBe("Note added to order 1002."));
expect(desk.orders.get("1002")!.notes).toEqual([{ by: "Ana Ruiz", note: "[Call back] Customer will call back after five." }]);
fireEvent.change(screen.getByRole("textbox", { name: /Order number/ }), { target: { value: "abc" } });
fireEvent.change(screen.getByRole("textbox", { name: /^Note/ }), { target: { value: "Second note" } });
fireEvent.click(screen.getByRole("button", { name: "Add note" }));
expect((await screen.findByRole("alert")).textContent).toMatch(/Fix the fields marked|Nothing ran/);
const order = screen.getByRole("textbox", { name: /Order number/ });
expect(order.getAttribute("aria-invalid")).toBe("true");
expect(screen.getByText("Not in the expected format.")).toBeTruthy();
expect(document.activeElement).toBe(order);
expect(desk.orders.get("1002")!.notes).toHaveLength(1);
});
it("asks in MUI's Dialog before a run that cannot be undone, with a reason and the word typed", async () => {
const { desk } = await open();
fireEvent.click(screen.getByRole("link", { name: "Review flags" }));
await screen.findByRole("heading", { name: "Review flags" });
fireEvent.change(screen.getByRole("textbox", { name: /Order number/ }), { target: { value: "1001" } });
fireEvent.click(screen.getByRole("button", { name: "Clear flag" }));
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText("This cannot be undone.")).toBeTruthy();
const allow = within(dialog).getByRole("button", { name: "Allow" });
expect(allow.getAttribute("aria-disabled")).toBe("true");
fireEvent.change(within(dialog).getByRole("textbox", { name: /Reason/ }), { target: { value: "Refund done." } });
fireEvent.change(within(dialog).getByRole("textbox", { name: /confirm/ }), { target: { value: "confirm" } });
expect(allow.hasAttribute("aria-disabled")).toBe(false);
fireEvent.click(allow);
await waitFor(() => expect(live()).toBe("Cleared the flag on order 1001."));
expect(desk.orders.get("1001")!.flagged).toBe(false);
// The run is in the backend's log, with who approved it and why; never the argument values.
const [run] = desk.operations.runs();
expect(run).toMatchObject({ operationId: "clear-flag" });
});
it("bundles MUI with no module of @surfaces-ui/components, icons or spec", async () => {
const here = import.meta.dirname;
const result = await build({
configFile: false,
root: here,
logLevel: "silent",
define: { "process.env.NODE_ENV": '"production"' },
build: { write: false, minify: true, lib: { entry: path.join(here, "App.tsx"), formats: ["es"], fileName: "app" }, rollupOptions: { output: { inlineDynamicImports: true } } },
});
const output = (Array.isArray(result) ? result : [result]).flatMap((r) => ("output" in r ? r.output : []));
const modules = output.flatMap((item) => (item.type === "chunk" ? Object.keys(item.modules) : [])).map((id) => id.replace(/\\/g, "/"));
const ours = [...new Set(modules.map((id) => /\/packages\/([^/]+)\//.exec(id)?.[1]).filter(Boolean))].sort();
expect(ours).toEqual(["document", "runtime", "trace"]);
expect(modules.some((id) => id.includes("@mui/material"))).toBe(true);
expect(modules.filter((id) => /@surfaces-ui\/(components|icons|spec)|echarts|codemirror/.test(id))).toEqual([]);
}, 180_000);
});In a browser
See it with pnpm --filter @surfaces-ui/recipes exec vite src/mui-components (?mode=dark for the dark palette). apps/e2e/tests/mui-components.spec.ts walks it in Chromium on every change, at desktop width in light and dark and at phone width: a note added, an order number refused at its field (focus on it), and a flag cleared through MUI's dialog, with axe's WCAG 2.2 AA checks and no console errors at each step. The pictures are taken by that test.
A note added; the shell announces what the run did:
The support desk drawn with MUI: an app bar, and a card with order number and note fields and an Add note button
The server refused the order number, and MUI's field shows its words:
The order number field in MUI's error state, with "Not in the expected format." under it
The same refusal at phone width
Approval in MUI's dialog, for a change that cannot be undone, in light and dark:
MUI's dialog: Clear flag?, "This cannot be undone.", a reason, "confirm" typed, and Allow
The same dialog in MUI's dark palette
Source and test: apps/recipes/src/mui-components