An app drawn with web components

Draw a Surfaces UI app document with your own web components: plain custom elements in shadow DOM, written with no framework, that any page can use. This takes the MUI recipe's support desk, document, catalog and backend unchanged, and draws it with a card, a text field, a select, a button, an alert and an approval dialog of the team's own. A catalog says what each component takes, not how it is drawn, so the same document runs with either set of renderers. Then it turns round, and the whole app becomes one element, <desk-app>, for a page that is not React.

It works both ways because the runtime renders through React 19, which handles custom elements as it does a <div>. It sets a property when the element has one (here the select's options array) and an attribute otherwise, and it listens for the element's own events by name: ondesk-input hears desk-input. No wrapper library is needed. Nothing from @surfaces-ui/components, @surfaces-ui/spec or any component library is installed or bundled.

The elements. Each draws a real, labelled control inside its shadow root, so a screen reader reaches it by name. Colours come from the page's --desk-* custom properties, which pass into every shadow root. A field shows the words it is given as error and marks itself invalid, and focus() puts focus in its box. <desk-confirm> asks in a modal <dialog>, and allows a change that cannot be undone only once "confirm" is typed:

elements.ts:

ts
// A team's own web components: plain custom elements with shadow DOM and no framework. Nothing here knows about
// Surfaces UI or React; any page can use them. Colours come from the page's `--desk-*` custom properties, which
// reach inside every shadow root.

const BASE = `
  :host { font: 16px/1.5 system-ui, sans-serif; color: var(--desk-text); }
  * { box-sizing: border-box; }
  :focus-visible { outline: 3px solid var(--desk-focus); outline-offset: 2px; }
  @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
`;

/** Gives an element an open shadow root with its styles and markup. */
function shadow(host: HTMLElement, css: string, html: string) {
  const root = host.attachShadow({ mode: "open" });
  root.innerHTML = `<style>${BASE}${css}</style>${html}`;
  return root;
}
let ids = 0;
const nextId = (prefix: string) => `${prefix}-${++ids}`;

/** `<desk-card heading="…">`: a bordered card with an optional heading over what is slotted in. */
export class DeskCard extends HTMLElement {
  static observedAttributes = ["heading"];
  readonly #title: HTMLElement;
  constructor() {
    super();
    const root = shadow(
      this,
      `section { display: grid; gap: 16px; padding: 16px; border: 1px solid var(--desk-border); border-radius: 8px; background: var(--desk-surface); }
       h2 { margin: 0; font-size: 1.25rem; font-weight: 600; } h2:empty { display: none; }
       ::slotted(*) { min-width: 0; }`,
      `<section part="card"><h2 part="heading"></h2><slot></slot></section>`,
    );
    this.#title = root.querySelector("h2")!;
  }
  attributeChangedCallback() {
    this.#title.textContent = this.getAttribute("heading") ?? "";
  }
}

/**
 * `<desk-field label="…" value="…" help="…" error="…" required multiline>`: a labelled text box. Fires `desk-input`
 * with what is typed (`detail`). With `error` the box is marked invalid and the words replace the help. `focus()`
 * puts focus in the box.
 */
export class DeskField extends HTMLElement {
  static observedAttributes = ["label", "value", "help", "error", "required", "multiline"];
  readonly #root: ShadowRoot;
  #box: HTMLInputElement | HTMLTextAreaElement | undefined;
  constructor() {
    super();
    this.#root = shadow(
      this,
      `.field { display: grid; gap: 4px; }
       label { font-weight: 600; } .required { font-weight: 400; color: var(--desk-muted); }
       input, textarea { font: inherit; color: var(--desk-text); background: var(--desk-input); width: 100%; min-height: 44px; padding: 8px 12px; border: 1px solid var(--desk-border-strong); border-radius: 6px; }
       textarea { min-height: 96px; resize: vertical; }
       [aria-invalid="true"] { border: 2px solid var(--desk-error); }
       .note { margin: 0; font-size: 0.875rem; color: var(--desk-muted); } .note:empty { display: none; }
       .note.error { color: var(--desk-error); font-weight: 600; }`,
      `<div class="field"><label></label><p class="note" aria-live="polite"></p></div>`,
    );
  }
  attributeChangedCallback(name: string) {
    // The box is made again only when it changes kind, so typing never loses focus or the caret.
    const multiline = this.hasAttribute("multiline");
    if (!this.#box || (name === "multiline" && (this.#box instanceof HTMLTextAreaElement) !== multiline)) this.#make(multiline);
    const box = this.#box!;
    const label = this.#root.querySelector("label")!;
    label.innerHTML = "";
    label.append(this.getAttribute("label") ?? "");
    if (this.hasAttribute("required")) label.insertAdjacentHTML("beforeend", ` <span class="required">(required)</span>`);
    const value = this.getAttribute("value") ?? "";
    if (box.value !== value) box.value = value;
    box.required = this.hasAttribute("required");
    const error = this.getAttribute("error");
    const note = this.#root.querySelector(".note")!;
    note.textContent = error || (this.getAttribute("help") ?? "");
    note.classList.toggle("error", !!error);
    if (error) box.setAttribute("aria-invalid", "true");
    else box.removeAttribute("aria-invalid");
  }
  #make(multiline: boolean) {
    const id = nextId("field");
    const box = document.createElement(multiline ? "textarea" : "input");
    box.id = id;
    const note = this.#root.querySelector(".note")!;
    note.id = `${id}-note`;
    box.setAttribute("aria-describedby", note.id);
    box.addEventListener("input", () => this.dispatchEvent(new CustomEvent("desk-input", { detail: box.value, bubbles: true, composed: true })));
    this.#root.querySelector("label")!.htmlFor = id;
    this.#box?.remove();
    note.before(box);
    this.#box = box;
  }
  override focus(options?: FocusOptions) {
    this.#box?.focus(options);
  }
}

/** `<desk-select label="…" value="…">` with `options` set as a property (`{ value, label }[]`). Fires `desk-input`. */
export class DeskSelect extends HTMLElement {
  static observedAttributes = ["label", "value"];
  readonly #root: ShadowRoot;
  #options: { value: string; label: string }[] = [];
  constructor() {
    super();
    const id = nextId("select");
    this.#root = shadow(
      this,
      `.field { display: grid; gap: 4px; } label { font-weight: 600; }
       select { font: inherit; color: var(--desk-text); background: var(--desk-input); min-height: 44px; padding: 8px 12px; border: 1px solid var(--desk-border-strong); border-radius: 6px; }`,
      `<div class="field"><label for="${id}"></label><select id="${id}"></select></div>`,
    );
    this.#root.querySelector("select")!.addEventListener("change", (event) => this.dispatchEvent(new CustomEvent("desk-input", { detail: (event.target as HTMLSelectElement).value, bubbles: true, composed: true })));
  }
  get options() {
    return this.#options;
  }
  set options(options: { value: string; label: string }[]) {
    this.#options = options;
    const select = this.#root.querySelector("select")!;
    select.replaceChildren(new Option("Choose one", ""), ...options.map((o) => new Option(o.label, o.value)));
    this.attributeChangedCallback();
  }
  attributeChangedCallback() {
    this.#root.querySelector("label")!.textContent = this.getAttribute("label") ?? "";
    this.#root.querySelector("select")!.value = this.getAttribute("value") ?? "";
  }
}

/**
 * `<desk-button variant="primary|secondary|danger" busy>label</desk-button>`: a button. Fires `desk-press`; while
 * `busy` it says so and does not fire.
 */
export class DeskButton extends HTMLElement {
  static observedAttributes = ["busy"];
  readonly #button: HTMLButtonElement;
  constructor() {
    super();
    const root = shadow(
      this,
      `button { font: inherit; font-weight: 600; min-height: 44px; min-width: 44px; padding: 8px 16px; border-radius: 6px; cursor: pointer;
         border: 1px solid var(--desk-accent); background: var(--desk-accent); color: var(--desk-on-accent); }
       :host([variant="secondary"]) button { background: transparent; color: var(--desk-accent-text); }
       :host([variant="danger"]) button { border-color: var(--desk-error); background: var(--desk-error); color: var(--desk-on-error); }
       [aria-disabled="true"] { opacity: 0.75; cursor: progress; }`,
      `<button part="button" type="button"><slot></slot></button>`,
    );
    this.#button = root.querySelector("button")!;
    this.#button.addEventListener("click", () => {
      if (!this.hasAttribute("busy")) this.dispatchEvent(new CustomEvent("desk-press", { bubbles: true, composed: true }));
    });
  }
  attributeChangedCallback() {
    if (this.hasAttribute("busy")) this.#button.setAttribute("aria-disabled", "true");
    else this.#button.removeAttribute("aria-disabled");
  }
}

/** `<desk-alert severity="info|warning|error">text</desk-alert>`. An error is announced (`role="alert"`). */
export class DeskAlert extends HTMLElement {
  static observedAttributes = ["severity"];
  readonly #box: HTMLElement;
  constructor() {
    super();
    const root = shadow(
      this,
      `div { padding: 12px 16px; border-radius: 6px; border-left: 4px solid var(--desk-info); background: var(--desk-info-bg); }
       :host([severity="warning"]) div { border-color: var(--desk-warning); background: var(--desk-warning-bg); }
       :host([severity="error"]) div { border-color: var(--desk-error); background: var(--desk-error-bg); }
       :host([severity="success"]) div { border-color: var(--desk-success); background: var(--desk-success-bg); }`,
      `<div part="alert"><slot></slot></div>`,
    );
    this.#box = root.querySelector("div")!;
  }
  attributeChangedCallback() {
    if (this.getAttribute("severity") === "error") this.#box.setAttribute("role", "alert");
    else this.#box.removeAttribute("role");
  }
}

/**
 * What `<desk-confirm>` asks about. */
export interface DeskQuestion {
  title: string;
  detail: string;
  reasonRequired?: boolean;
  irreversible?: boolean;
}
/** A person's answer: allowed or not, and why. */
export interface DeskAnswer {
  allow: boolean;
  reason: string;
}

/**
 * `<desk-confirm>`: asks a person to approve something, in a modal `<dialog>`. `ask(question)` resolves with their
 * answer, or with nothing if they cancel. A reason is asked for where one is required, and a change that cannot be
 * undone is allowed only once they type "confirm".
 */
export class DeskConfirm extends HTMLElement {
  readonly #root: ShadowRoot;
  constructor() {
    super();
    this.#root = shadow(
      this,
      `dialog { width: min(520px, calc(100vw - 32px)); border: 1px solid var(--desk-border); border-radius: 8px; padding: 24px; background: var(--desk-surface); color: var(--desk-text); }
       dialog::backdrop { background: rgb(0 0 0 / 0.5); }
       h2 { margin: 0 0 8px; font-size: 1.25rem; } p { margin: 0 0 12px; }
       .warning { padding: 8px 12px; border-left: 4px solid var(--desk-warning); background: var(--desk-warning-bg); font-weight: 600; }
       .actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 16px; }
       [hidden] { display: none !important; }`,
      `<dialog aria-labelledby="t" aria-describedby="d">
         <h2 id="t"></h2><p id="d"></p><p class="warning" hidden>This cannot be undone.</p>
         <desk-field class="reason" label="Reason" required multiline hidden></desk-field>
         <desk-field class="word" label='Type "confirm" to allow it' hidden></desk-field>
         <div class="actions">
           <desk-button class="cancel" variant="secondary">Cancel</desk-button>
           <desk-button class="no" variant="secondary">Don't allow</desk-button>
           <desk-button class="yes">Allow</desk-button>
         </div>
       </dialog>`,
    );
  }
  ask(request: DeskQuestion): Promise<DeskAnswer | undefined> {
    const $ = <T extends Element>(selector: string) => this.#root.querySelector<T>(selector)!;
    const dialog = $<HTMLDialogElement>("dialog");
    const irreversible = request.irreversible === true;
    const reason = $<DeskField>(".reason");
    const word = $<DeskField>(".word");
    let typedReason = "";
    let typedWord = "";
    $("h2").textContent = request.title;
    $("#d").textContent = request.detail;
    $<HTMLElement>(".warning").hidden = !irreversible;
    reason.hidden = !request.reasonRequired;
    word.hidden = !irreversible;
    reason.setAttribute("value", "");
    word.setAttribute("value", "");
    const yes = $<DeskButton>(".yes");
    yes.setAttribute("variant", irreversible ? "danger" : "primary");
    const ready = () => (!request.reasonRequired || typedReason.trim() !== "") && (!irreversible || typedWord.trim().toLowerCase() === "confirm");
    const mark = () => yes.shadowRoot!.querySelector("button")!.setAttribute("aria-disabled", String(!ready()));
    mark();
    return new Promise((resolve) => {
      const listeners = new AbortController();
      const done = (answer: DeskAnswer | undefined) => {
        listeners.abort();
        if (typeof dialog.close === "function") dialog.close();
        else dialog.removeAttribute("open");
        resolve(answer);
      };
      const { signal } = listeners;
      reason.addEventListener("desk-input", (e) => ((typedReason = (e as CustomEvent<string>).detail), mark()), { signal });
      word.addEventListener("desk-input", (e) => ((typedWord = (e as CustomEvent<string>).detail), mark()), { signal });
      $(".cancel").addEventListener("desk-press", () => done(undefined), { signal });
      $(".no").addEventListener("desk-press", () => done({ allow: false, reason: typedReason }), { signal });
      yes.addEventListener("desk-press", () => ready() && done({ allow: true, reason: typedReason }), { signal });
      dialog.addEventListener("cancel", () => done(undefined), { signal });
      if (typeof dialog.showModal === "function") dialog.showModal();
      else dialog.setAttribute("open", "");
    });
  }
}

/** Defines every element once, whatever imports this. */
export function defineDeskElements() {
  const all = { "desk-card": DeskCard, "desk-field": DeskField, "desk-select": DeskSelect, "desk-button": DeskButton, "desk-alert": DeskAlert, "desk-confirm": DeskConfirm };
  for (const [name, element] of Object.entries(all)) if (!customElements.get(name)) customElements.define(name, element);
}

The renderers: one per catalog component, returning the elements. As in the MUI recipe, three of them draw what an operation's server said: Field passes the server's refusal to its element and moves focus there (useRunFieldError), Press marks the button busy and shows a refusal under it (useRunState), and confirmWith asks the runtime's approval request in <desk-confirm>. A custom element's events and properties need a JSX type, declared at the top:

renderers.tsx:

tsx
// The MUI recipe's catalog drawn with the team's own web components (elements.ts) instead of MUI. React 19 sets a
// custom element's properties and listens for its events by name (`ondesk-input` for `desk-input`), so a renderer
// returns the element as it would a <div>. Three renderers draw what an operation's server said: a field the server
// refused, a button's run, and the approval asked in `<desk-confirm>`.
import { type AppNavProps, type ComponentRenderer, RUN_RISK, type RunAnswer, type RunApproval, useAppLinks, useRunFieldError, useRunState } from "@surfaces-ui/runtime";
import { useEffect, useRef } from "react";
import type { DeskConfirm, DeskField, DeskSelect } from "./elements.js";

type Base = { children?: React.ReactNode; class?: string; ref?: React.Ref<HTMLElement> };
type Input = { "ondesk-input"?: (event: CustomEvent<string>) => void };
declare module "react" {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace JSX {
    interface IntrinsicElements {
      "desk-card": Base & { heading?: string };
      "desk-field": Base & Input & { label: string; value: string; help?: string; error?: string; required?: boolean; multiline?: boolean };
      "desk-select": Base & Input & { label: string; value: string; options: { value: string; label: string }[] };
      "desk-button": Base & { variant?: string; busy?: boolean; "ondesk-press"?: () => void };
      "desk-alert": Base & { severity?: string };
      "desk-confirm": Base;
    }
  }
}

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({ label, value, path, multiline, help, required, change }: { label: string; value: string; path?: string; multiline?: boolean; help?: string; required?: boolean; change(value: string): void }) {
  const refused = useRunFieldError(path);
  const field = useRef<DeskField>(null);
  useEffect(() => {
    if (refused.first) field.current?.focus();
  }, [refused.first, refused.at]);
  return <desk-field ref={field as React.Ref<HTMLElement>} label={label} value={value} help={help} error={refused.message} required={required || undefined} multiline={multiline || undefined} ondesk-input={(event) => change(event.detail)} />;
}

function Choice({ label, value, options, change }: { label: string; value: string; options: { value: string; label: string }[]; change(value: string): void }) {
  // `options` is an array, so it is set as a property; React 19 does that because the element has one.
  const select = useRef<DeskSelect>(null);
  return <desk-select ref={select as React.Ref<HTMLElement>} label={label} value={value} options={options} ondesk-input={(event) => change(event.detail)} />;
}

function Press({ id, label, variant, color, press }: { id: string; label: string; variant?: string; color?: string; 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 (
    <div className="desk-press">
      <desk-button variant={color === "error" ? "danger" : variant === "contained" || !variant ? "primary" : "secondary"} busy={working || undefined} ondesk-press={press}>
        {working ? `${label}…` : label}
      </desk-button>
      {refused && <desk-alert severity="error">{state.message}</desk-alert>}
      {reread && (
        <desk-button variant="secondary" ondesk-press={reread}>
          Read again
        </desk-button>
      )}
    </div>
  );
}

function AppLink({ text, to }: { text: string; to: string }) {
  const links = useAppLinks();
  return (
    <a
      className="desk-link"
      href={links ? links.href(to) : to}
      onClick={(event) => {
        if (!links || event.metaKey || event.ctrlKey) return;
        event.preventDefault();
        links.go(to);
      }}
    >
      {text}
    </a>
  );
}

export const deskRenderers: Record<string, ComponentRenderer> = {
  Stack: ({ props, component, children }) => <div className={`desk-stack${props.direction === "row" ? " row" : ""}`}>{children(component.children)}</div>,
  Card: ({ props, component, children }) => (
    <desk-card heading={props.title ? words(props.title) : undefined}>
      <div className="desk-stack">{children(component.children)}</div>
    </desk-card>
  ),
  Heading: ({ props }) => (props.level === 2 ? <h2 className="desk-h2">{words(props.text)}</h2> : <h1>{words(props.text)}</h1>),
  Text: ({ props }) => <p className={`desk-text${props.tone === "secondary" ? " secondary" : ""}`}>{words(props.text)}</p>,
  TextField: ({ props, component, setData }) => (
    <Field label={words(props.label)} value={words(props.value)} path={pathOf(component.value)} multiline={props.multiline === true} help={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 string} color={props.color as string} press={() => dispatch(component.action)} />,
  Link: ({ props }) => <AppLink text={words(props.text)} to={words(props.to)} />,
  Alert: ({ props }) => <desk-alert severity={(props.severity as string) ?? "info"}>{words(props.text)}</desk-alert>,
  Divider: () => <hr />,
};

/** The app's navigation: a bar of links, the current one marked. */
export function deskNav({ title, items, go }: AppNavProps) {
  return (
    <nav className="desk-bar" aria-label={title}>
      <p>{title}</p>
      {items.map((item) => (
        <a
          key={item.to}
          href={item.href}
          aria-current={item.current ? "page" : undefined}
          onClick={(event) => {
            event.preventDefault();
            go(item.to);
          }}
        >
          {item.label}
        </a>
      ))}
    </nav>
  );
}

/** The runtime's approval request asked in a `<desk-confirm>` element. */
export const confirmWith = (element: () => DeskConfirm | null) => async (request: RunApproval): Promise<RunAnswer | undefined> =>
  element()?.ask({ title: request.title, detail: request.detail, reasonRequired: request.reasonRequired, irreversible: request.risk === RUN_RISK.irreversible });

The look: the custom properties, light and dark, and the layout around the elements:

theme.ts:

ts
// The desk's look: custom properties every element reads (they reach inside shadow roots), and the layout of the
// page around the elements. Light and dark; text and controls read at 4.5:1 or more on their backgrounds.
export const deskTheme = `
  :host, :root {
    --desk-bg: #f6f7f9; --desk-surface: #ffffff; --desk-input: #ffffff; --desk-text: #1d2433; --desk-muted: #4a5468;
    --desk-border: #d5d9e0; --desk-border-strong: #6b7385; --desk-accent: #1f5fbf; --desk-accent-text: #1a52a6; --desk-on-accent: #ffffff;
    --desk-focus: #1f5fbf; --desk-error: #b3261e; --desk-on-error: #ffffff; --desk-error-bg: #fbeae9;
    --desk-warning: #8a5a00; --desk-warning-bg: #fdf3dc; --desk-info: #1f5fbf; --desk-info-bg: #e8f0fb; --desk-success: #1e6b3a; --desk-success-bg: #e6f4ea;
  }
  :host([mode="dark"]), :root[data-mode="dark"] {
    --desk-bg: #111418; --desk-surface: #1b1f26; --desk-input: #11151a; --desk-text: #e8ebf0; --desk-muted: #b4bccb;
    --desk-border: #323844; --desk-border-strong: #8790a0; --desk-accent: #8ab4f8; --desk-accent-text: #8ab4f8; --desk-on-accent: #0d1b33;
    --desk-focus: #8ab4f8; --desk-error: #f2b8b5; --desk-on-error: #3b0a07; --desk-error-bg: #3a1c1b;
    --desk-warning: #f0c060; --desk-warning-bg: #352a12; --desk-info: #8ab4f8; --desk-info-bg: #18243a; --desk-success: #8fd19e; --desk-success-bg: #15291b;
  }
  :host { display: block; min-height: 100vh; background: var(--desk-bg); color: var(--desk-text); font: 16px/1.5 system-ui, sans-serif; }
  .desk-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 16px; background: var(--desk-surface); border-bottom: 1px solid var(--desk-border); }
  .desk-bar p { margin: 0 16px 0 0; font-weight: 700; font-size: 1.125rem; }
  .desk-bar a { display: inline-flex; align-items: center; min-height: 44px; padding: 0 12px; border-radius: 6px; color: var(--desk-accent-text); font-weight: 600; text-decoration: none; }
  .desk-bar a[aria-current="page"] { outline: 2px solid var(--desk-accent); outline-offset: -2px; }
  .desk-bar a:focus-visible, .desk-link:focus-visible { outline: 3px solid var(--desk-focus); outline-offset: 2px; }
  main { max-width: 760px; margin: 0 auto; padding: 24px 16px; }
  .desk-stack { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
  .desk-stack.row { flex-direction: row; flex-wrap: wrap; }
  .desk-press { display: grid; gap: 8px; justify-items: start; }
  h1 { margin: 0; font-size: 2rem; line-height: 1.2; }
  h2.desk-h2 { margin: 0; font-size: 1.25rem; }
  p.desk-text { margin: 0; } p.desk-text.secondary { color: var(--desk-muted); }
  .desk-link { color: var(--desk-accent-text); }
  hr { width: 100%; border: 0; border-top: 1px solid var(--desk-border); }
  .sf-app-live { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
`;

The shell: validateApp with the backend's operations before anything is drawn, AppView with the elements in every slot, and one <desk-confirm> beside it:

App.tsx:

tsx
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 { useRef } from "react";
// The same document and catalog as the MUI recipe: a catalog says what each component takes, not how it is drawn.
import { deskApp } from "../mui-components/app.js";
import { muiCatalog } from "../mui-components/catalog.js";
import { type DeskConfirm, defineDeskElements } from "./elements.js";
import { confirmWith, deskNav, deskRenderers } from "./renderers.js";

defineDeskElements();

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"];
}

/** The whole app: one document drawn with web components, approval asked in `<desk-confirm>`, the address in the hash. */
export function App({ operations, operationDefinitions, digest }: DeskProps) {
  const location = useHashLocation();
  const dialog = useRef<DeskConfirm>(null);
  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 (
    <>
      <AppView app={deskApp} catalog={muiCatalog} renderers={deskRenderers} nav={deskNav} operations={operations} operationDefinitions={operationDefinitions} confirm={confirmWith(() => dialog.current)} digest={digest} {...location} />
      <desk-confirm ref={dialog as React.Ref<HTMLElement>} />
    </>
  );
}

The whole app as one element. <desk-app> draws the shell into its own shadow root with the desk's styles there, so the page's CSS does not reach in and the app's does not leak out. A page needs only the element and one script; mode="dark" switches the palette:

mount.tsx:

tsx
// The other way round: the whole app as one web component, `<desk-app>`, for a page that is not React. It draws into
// its own shadow root, with the desk's styles there, so nothing on the page reaches in and nothing leaks out.
import { approvalDigest } from "@surfaces-ui/data";
import { type Root, createRoot } from "react-dom/client";
import { App } from "./App.js";
import { supportDesk } from "../mui-components/desk.js";
import { deskTheme } from "./theme.js";

export class DeskApp extends HTMLElement {
  #root: Root | undefined;
  async connectedCallback() {
    const shadow = this.shadowRoot ?? this.attachShadow({ mode: "open" });
    shadow.innerHTML = `<style>${deskTheme}</style><div></div>`;
    // The desk's backend runs in memory here; yours is a server, reached with `httpOperations` (see own-operations).
    const desk = supportDesk();
    const { operations: operationDefinitions } = await desk.operations.listOperations({});
    this.#root = createRoot(shadow.querySelector("div")!);
    this.#root.render(<App operations={desk.operations} operationDefinitions={operationDefinitions} digest={approvalDigest} />);
  }
  disconnectedCallback() {
    this.#root?.unmount();
  }
}

if (!customElements.get("desk-app")) customElements.define("desk-app", DeskApp);

The test draws the document with the elements and adds a note through them (the app's state follows their desk-input events). It has the server refuse an order number and finds the refusal inside the element, with focus in its box, and clears a flag through <desk-confirm>, which does nothing until a reason and "confirm" are typed. It also runs the app as <desk-app> with nothing outside the element on the page, then bundles the shell to show that, of this repository's packages, only document, runtime and trace are in it, with no component library:

web-components.test.tsx:

tsx
// @vitest-environment jsdom
import path from "node:path";
import { approvalDigest } from "@surfaces-ui/data";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { build } from "vite";
import { afterEach, describe, expect, it } from "vitest";
import { supportDesk } from "../mui-components/desk.js";
import { App } from "./App.js";
import "./mount.js";

afterEach(() => {
  cleanup();
  document.body.innerHTML = "";
  window.location.hash = "";
});

// The elements keep their insides in open shadow roots; these reach in the way a person's screen reader does.
const inside = (host: Element, selector: string) => host.shadowRoot!.querySelector(selector) as HTMLElement;
const field = (root: ParentNode, label: string) => [...root.querySelectorAll("desk-field")].find((f) => f.getAttribute("label") === label)!;
const type = (host: Element, value: string) => {
  const box = inside(host, "input, textarea") as HTMLInputElement;
  fireEvent.input(box, { target: { value } });
};
const press = (root: ParentNode, label: string) => {
  const button = [...root.querySelectorAll("desk-button")].find((b) => b.textContent?.trim() === label)!;
  fireEvent.click(inside(button, "button"));
};
const live = (root: ParentNode = document) => root.querySelector(".sf-app-live")!.textContent!.trim();

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;
}

describe("an app drawn with web components", () => {
  it("draws the MUI recipe's document with custom elements, and adds a note through them", async () => {
    const desk = await open();
    const order = field(document, "Order number");
    // React 19 set the element's attributes, and the element drew a real, labelled input in its shadow root.
    expect(order.getAttribute("required")).toBe("");
    const box = inside(order, "input") as HTMLInputElement;
    expect(inside(order, "label").textContent).toContain("Order number");
    expect(inside(order, "label").getAttribute("for")).toBe(box.id);
    type(order, "1002");
    type(field(document, "Note"), "Customer will call back after five.");
    // The app's state followed the element's `desk-input` events, and is kept in the address.
    await waitFor(() => expect(window.location.hash).toContain("orderId=1002"));
    expect(order.getAttribute("value")).toBe("1002");
    press(document, "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." }]);
  });

  it("shows the server's refusal inside the element at the field it named, and moves focus there", async () => {
    const desk = await open();
    const order = field(document, "Order number");
    type(order, "abc");
    type(field(document, "Note"), "Second note");
    press(document, "Add note");
    await waitFor(() => expect(order.getAttribute("error")).toBe("Not in the expected format."));
    const box = inside(order, "input");
    expect(box.getAttribute("aria-invalid")).toBe("true");
    expect(inside(order, ".note").textContent).toBe("Not in the expected format.");
    expect(order.shadowRoot!.activeElement).toBe(box);
    expect([...desk.orders.values()].flatMap((o) => o.notes)).toEqual([]);
  });

  it("asks in <desk-confirm> before a change 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" });
    type(field(document, "Order number"), "1001");
    press(document, "Clear flag");
    const confirm = document.querySelector("desk-confirm")!;
    const dialog = inside(confirm, "dialog");
    await waitFor(() => expect(dialog.hasAttribute("open")).toBe(true));
    expect(inside(confirm, "h2").textContent).toBe("Clear flag?");
    expect(inside(confirm, ".warning").hidden).toBe(false);
    const allow = inside(confirm, ".yes");
    expect(inside(allow, "button").getAttribute("aria-disabled")).toBe("true");
    press(confirm.shadowRoot!, "Allow");
    expect(desk.orders.get("1001")!.flagged).toBe(true);
    type(inside(confirm, ".reason"), "Refund done.");
    type(inside(confirm, ".word"), "confirm");
    expect(inside(allow, "button").getAttribute("aria-disabled")).toBe("false");
    press(confirm.shadowRoot!, "Allow");
    await waitFor(() => expect(live()).toBe("Cleared the flag on order 1001."));
    expect(desk.orders.get("1001")!.flagged).toBe(false);
    expect(desk.operations.runs()[0]).toMatchObject({ operationId: "clear-flag" });
  });

  it("runs as one element, <desk-app>, drawn into its own shadow root", async () => {
    const app = document.createElement("desk-app");
    document.body.append(app);
    await waitFor(() => expect(app.shadowRoot!.querySelector("h1")?.textContent).toBe("Add a note to an order"));
    // The page's own markup holds only the element; everything else is inside it.
    expect(document.body.querySelectorAll("h1, input, desk-field")).toHaveLength(0);
    const root = app.shadowRoot!;
    type(field(root, "Order number"), "1003");
    type(field(root, "Note"), "Left a voicemail.");
    press(root, "Add note");
    await waitFor(() => expect(live(root)).toBe("Note added to order 1003."));
  });

  it("bundles with no module of @surfaces-ui/components, icons or spec, and no component library", 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.filter((id) => /@surfaces-ui\/(components|icons|spec)|@mui|@emotion|echarts|codemirror/.test(id))).toEqual([]);
  }, 180_000);
});

In a browser

See it with pnpm --filter @surfaces-ui/recipes exec vite src/web-components (?mode=dark for dark). The page is one <desk-app> element. apps/e2e/tests/web-components.spec.ts walks it in Chromium on every change, at desktop width in light and dark and at phone width. Every control is found by its accessible name through the shadow roots, the refusal moves focus into the element's box, and the approval is a real modal dialog. Axe's WCAG 2.2 AA checks pass and there are 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 web components: a bar of links, and a card with order number, kind and note fields and an Add note button

The server refused the order number. <desk-field> shows its words and is marked invalid, with focus in it:

The order number field marked invalid, with "Not in the expected format." under it

The same refusal at phone width

Approval in <desk-confirm>, for a change that cannot be undone, in light and dark:

The approval dialog: Clear flag?, "This cannot be undone.", a reason, "confirm" typed, and Allow

The same dialog in dark mode

Source and test: apps/recipes/src/web-components