A dashboard a person can arrange

Any page drawn from a PageDocument can offer Arrange: a person drags a component by its bar to before or after another, to the side zone of one to put the two side by side (where they would be drawn side by side), or into a container; a line, the container that takes it and the half a new column would take are drawn while it moves, and a page that lays out across has bands above and below everything; drags the handle under it to change its height, or at its right edge to change widths. Every drag has a keyboard form (the bar's arrows, arrow keys on the handles), and drags use pointer events, so they work by touch and pen.

Arranging is an option, never a dependency. The page draws the same with it off, and what Arrange sends is the same JSON an agent sends to arrange a page: the order of children, widths on a Grid or Row, and height or minHeight. So a page arranged by hand can be changed by an agent afterwards, and the other way round.

How it works:

  • useArrange from @surfaces-ui/spec/react takes the surface and three functions: apply (A2UI messages to take in as one step), say (what happened, or why it could not be done) and remove.
  • apply turns the messages into page edits with editsFromMessages and applies them with editPage, which checks each against the catalog. A move between containers arrives as two components; the edits keep the component that moved.
  • Pass arrange.surfaceFrame to SurfaceView as frame and draw arrange.shown(surface), so a size being dragged is drawn as it will be. While arranging, surfaceFrame is Arrange's frames; with resizeWhileViewing: true it keeps only the size handles while nobody is arranging (between a Grid's or Row's columns, and under a component with a height of its own (a chart or a table, say) or one whose height is set), and each drag is the same one step Arrange would make. Moving and removing stay inside Arrange. Put arrange.region on the element around the surface: it quiets the components' own controls so only one layer shows.
  • The handles are ResizeHandle from @surfaces-ui/components, which an app can also place on its own: arrows, Home and End, and Enter or a double click to reset (the widths and height the page shipped with when useArrange is given shipped; equal widths and the height the component chooses otherwise).
  • The marks for where it will land are drawn over the surface by useArrange itself. arrange.toPageSide and arrange.toPageEnd are the menu and keyboard forms of a column down the page and of above or below everything, for you to offer; arrange.drag carries a drag of your own (a component from a panel).
  • ArrangeToggle, ArrangeHelp and ArrangeGhost are the button, the help and status line, and the chip that follows the pointer.

PageStudio from @surfaces-ui/chat does all of this with arrange, logs each arrangement by the person who made it, and tells the agent about it with the next instruction. Use this recipe when the page is not in a studio: a saved dashboard, a report, or any multi-view page of your own.

ArrangeableDashboard.tsx:

tsx
import { type PageDocument, analyticsCatalog, editPage, editsFromMessages, pageSurface, removeComponentMessages } from "@surfaces-ui/spec";
import { ArrangeGhost, ArrangeHelp, ArrangeToggle, SurfaceView, analyticsRenderers, useArrange } from "@surfaces-ui/spec/react";
import { useMemo, useState } from "react";

/**
 * A saved dashboard (a `PageDocument`) a person can rearrange by hand.
 * Arranging is optional: the page draws the same with it off, and an agent
 * arranges the same page by sending the same props (`children`, `widths`,
 * `height`). Every change is one step to undo.
 */
export function ArrangeableDashboard({ initial, onChange }: { initial: PageDocument; onChange?(page: PageDocument): void }) {
  const [history, setHistory] = useState<PageDocument[]>([initial]);
  const page = history.at(-1)!;
  const [status, setStatus] = useState<{ text: string; error?: boolean }>();
  const surface = useMemo(() => pageSurface(page), [page]);

  /** Takes in what Arrange sends, as page edits the catalog checks, and keeps it as one step. */
  const apply = (messages: Parameters<typeof editsFromMessages>[1]) => {
    const { page: next, rejected } = editPage(page, editsFromMessages(page, messages), analyticsCatalog);
    if (rejected.length > 0) return setStatus({ text: rejected[0]!.reason, error: true });
    setHistory((steps) => [...steps, next]);
    onChange?.(next);
  };

  const arrange = useArrange({
    surface,
    apply,
    say: setStatus,
    remove: (id) => {
      const result = removeComponentMessages(surface, id);
      if ("error" in result) setStatus({ text: result.error, error: true });
      else apply(result.messages);
    },
    // Widths and set heights can be dragged without turning Arrange on; moving and removing still need it.
    resizeWhileViewing: true,
  });

  return (
    <section aria-label={page.title}>
      <div>
        <ArrangeToggle arrange={arrange} />
        <button type="button" className="sf-button" disabled={history.length === 1} onClick={() => setHistory((steps) => steps.slice(0, -1))}>
          Undo
        </button>
      </div>
      <ArrangeHelp arrange={arrange} status={status} />
      <div {...arrange.region} className={`sf-container ${arrange.region.className}`}>
        <SurfaceView
          surface={arrange.shown(surface)}
          catalog={analyticsCatalog}
          renderers={analyticsRenderers}
          {...(arrange.surfaceFrame ? { frame: arrange.surfaceFrame } : {})}
        />
      </div>
      <ArrangeGhost arrange={arrange} />
    </section>
  );
}

The test draws a real page against memoryDataSource, widens a column with the keyboard while viewing, moves a number earlier with its control, removes the title, and undoes the removal. Pointer drags and the resize handles are covered by the playground's browser tests, since jsdom has no layout.

arrange.test.tsx:

tsx
// @vitest-environment jsdom
import { DataSourceProvider } from "@surfaces-ui/components";
import { memoryDataSource } from "@surfaces-ui/data";
import { type PageDocument, analyticsCatalog } from "@surfaces-ui/spec";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { ArrangeableDashboard } from "./ArrangeableDashboard.js";

afterEach(cleanup);

const sql = "SELECT * FROM orders";
const page: PageDocument = {
  id: "sales",
  title: "Sales",
  catalogId: analyticsCatalog.id,
  components: [
    { id: "root", component: "Column", children: ["title", "numbers"] },
    { id: "title", component: "Text", text: "Sales", variant: "h1" },
    { id: "numbers", component: "Grid", columns: 2, children: ["revenue", "orders"] },
    { id: "revenue", component: "Metric", sourceId: "shop", sql, column: "amount", aggregate: "sum", label: "Revenue" },
    { id: "orders", component: "Metric", sourceId: "shop", sql, aggregate: "count", label: "Orders" },
  ],
};
const data = memoryDataSource({ sourceId: "shop", tables: { orders: [{ id: 1, amount: 10 }, { id: 2, amount: 32 }] } });
const children = (p: PageDocument, id: string) => p.components.find((c) => c.id === id)?.children;

describe("a dashboard a person can arrange", () => {
  it("moves and removes components by their controls, keeps each change as a page edit, and undoes it", async () => {
    const pages: PageDocument[] = [];
    render(
      <DataSourceProvider dataSource={data}>
        <ArrangeableDashboard initial={page} onChange={(next) => pages.push(next)} />
      </DataSourceProvider>,
    );
    // Off by default: the page is drawn as saved, with no frames.
    expect(document.querySelector(".sf-arrange-frame")).toBeNull();

    // While viewing, the line between the two numbers still sizes them: one key press is one step.
    const line = screen.getByRole("separator", { name: "Resize Metric revenue and what is to its right: wider or narrower" });
    expect(line.getAttribute("aria-valuenow")).toBe("50");
    fireEvent.keyDown(line, { key: "ArrowRight" });
    await waitFor(() => expect(pages.at(-1)!.components.find((c) => c.id === "numbers")?.widths).toEqual([0.54, 0.46]));
    fireEvent.keyDown(screen.getByRole("separator", { name: /Resize Metric revenue/ }), { key: "Enter" });
    await waitFor(() => expect(pages.at(-1)!.components.find((c) => c.id === "numbers")?.widths).toEqual([0.5, 0.5]));
    fireEvent.click(screen.getByRole("button", { name: "Arrange" }));
    expect(screen.getByRole("button", { name: "Done arranging" })).toHaveProperty("ariaPressed", "true");

    // The same controls a report's tiles have: move "orders" earlier in its grid.
    fireEvent.click(screen.getByRole("button", { name: "Move Metric orders earlier" }));
    await waitFor(() => expect(children(pages.at(-1)!, "numbers")).toEqual(["orders", "revenue"]));
    expect(screen.getByRole("status").textContent).toContain('Moved "orders" earlier');

    // Removing takes it off the page, not just out of its container.
    fireEvent.click(screen.getByRole("button", { name: "Remove Text title" }));
    await waitFor(() => expect(pages.at(-1)!.components.some((c) => c.id === "title")).toBe(false));
    expect(children(pages.at(-1)!, "root")).toEqual(["numbers"]);

    // Each change was one step.
    fireEvent.click(screen.getByRole("button", { name: "Undo" }));
    await waitFor(() => expect(screen.getByRole("button", { name: "Remove Text title" })).toBeTruthy());
  });
});

Source and test: apps/recipes/src/arrange-dashboard