Get started

Headless studio

A segment list drawn in plain ul, li and button markup that renames and deletes through the studio's own verbs. It ships no design system and no map renderer.

A plain segment list with rename and delete buttons

The files

Every file the app needs, as it builds in the SDK repository. src/App.tsx wires the studio by hand, and src/SegmentList.tsx is your markup.

From examples/studio-headless/package.json
{
  "name": "@mountaya/example-studio-headless",
  "version": "0.0.0",
  "private": true,
  "license": "MIT",
  "description": "A Vite application that renders a segment list with its own markup, on the studio's own verbs.",
  "type": "module",
  "scripts": {
    "build": "vite build",
    "dev": "vite",
    "lint": "tsc --noEmit"
  },
  "dependencies": {
    "@mountaya/client": "0.1.0",
    "@mountaya/client-react": "0.1.0",
    "@mountaya/elements": "0.1.0",
    "@mountaya/elements-react": "0.1.0",
    "@mountaya/studio": "0.1.0",
    "@mountaya/studio-react": "0.1.0",
    "@tanstack/react-query": "^5",
    "maplibre-gl": "6.18.0",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "@types/react": "19.3.0",
    "@types/react-dom": "19.3.0",
    "@vitejs/plugin-react": "6.1.2",
    "typescript": "7.0.2",
    "vite": "8.3.4"
  }
}
From examples/studio-headless/vite.config.ts
import react from "@vitejs/plugin-react";
import { defaultClientConditions, defineConfig } from "vite";

/**
 * The example builds against the packages' SOURCE, not their `dist`.
 *
 * `@mountaya/source` is the condition every package in this family publishes its own TypeScript
 * under, and naming it here is what makes this example a gate rather than a demo: a change to a
 * component is compiled by this build on the next run, with no `npm run build` in between. A
 * demo pointed at `dist` would go on succeeding against whatever was built last, which is the
 * failure mode an example exists to catch.
 *
 * It is also the one thing in this file a consumer should NOT copy. Their bundler resolves the
 * published `dist` under the default conditions, which is what `scripts/packaging.test.mjs`
 * holds every package to (its "resolves to source only under the scoped condition" rule).
 */
export default defineConfig({
  plugins: [react()],
  resolve: {
    // Vite replaces its default conditions with a list a config names, so they follow the
    // condition: without them a dependency loses `module`, `browser` and `development|production`.
    conditions: ["@mountaya/source", ...defaultClientConditions],
  },
});
From examples/studio-headless/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <title>Mountaya studio, headless</title>
  </head>
  <body>
    <!-- No stylesheet is imported anywhere in this application. That is the point of it: the
         markup below is the consumer's, so the styling is too. -->
    <div id="root"></div>
    <script src="/src/main.tsx" type="module"></script>
  </body>
</html>
From examples/studio-headless/src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import { App } from "./App.js";

/**
 * The mount, and the whole of what this file is.
 *
 * No stylesheet import, unlike `examples/studio-vite/src/main.tsx`. That difference is the
 * example: `@mountaya/studio-react/headless` brings no design system and paints nothing, so
 * there is no sheet to import and nothing to theme.
 *
 * StrictMode is on deliberately. It double-invokes effects in development, which is what finds
 * a store subscription that does not survive being mounted twice, and a consumer's application
 * will have it on.
 */
const container = document.querySelector("#root");

if (container === null) {
  throw new Error("index.html has no #root to mount into.");
}

createRoot(container).render(
  <StrictMode>
    <App />
  </StrictMode>,
);
From examples/studio-headless/src/App.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { type ReactNode, useMemo, useState } from "react";

import { Mountaya } from "@mountaya/client/browser";
import {
  MountayaProvider,
  useItinerary,
  useMountaya,
  useSessionToken,
} from "@mountaya/client-react";
import {
  createStaticViewer,
  createUiStore,
  persistedItineraryView,
  restStudioPersistence,
  type StudioToolContext,
} from "@mountaya/studio";
import { createStudioToolBus } from "@mountaya/studio/handlers";
import { browserSaveFile } from "@mountaya/studio/seams";
import { MountayaStudioProvider, useStudioCache } from "@mountaya/studio-react/headless";

import { SegmentList } from "./SegmentList.js";

const PUBLISHABLE_KEY = "pk_…";
const USER_ID = "user_…";
const ITINERARY_ID = "itin_…";

const queryClient = new QueryClient();

/**
 * Mints the session token the draft is read and written under.
 *
 * Minting takes the secret key, so your server does it: this endpoint calls `POST /v1/sessions`
 * with `{ publishable_key, surface: "studio-embedded", user_id }` and returns the
 * `{ token, expires_at, user_id }` it receives. `surface` is the studio's own, the only one a
 * `studio-embedded` write accepts. `user_id` is the member your own sign-in vouches for, read from
 * your server's session and never from the request, and it is USER_ID: every write acts as the
 * user the token names. An answer that is not a success rejects, so the hook reports it and asks
 * again.
 */
const mintSession = async () => {
  const response = await fetch("/api/mountaya-session");
  if (!response.ok) {
    throw new Error(`The session endpoint answered ${response.status}.`);
  }

  return response.json();
};

/**
 * The wiring `MountayaStudioHost` does for you, done by hand.
 *
 * This is the cost of the headless entry and the reason the assembled host exists: a store, a
 * bus with the studio's own handlers registered on it, and the context the bus dispatches with.
 * The context is typed as what it is, so a member a handler reads and this literal leaves out
 * is a compile error here and not a throw inside a dispatch.
 *
 * `capabilities` is the one thing a real application derives and does not state: a viewer's
 * grants come from their membership, and a surface that hard-codes `editor` renders controls the
 * server refuses. `saveFile` is the page's own download, because this application runs in one;
 * a host with no document names `inertStudioSaveFile` or a save of its own.
 */
const Wired = ({ children }: { readonly children: ReactNode }) => {
  const mountaya = useMountaya();
  // The studio's cache seam, over the query cache this application reads through and under the
  // provider's credential. A handler names the resource it wrote and never a key: a rename that
  // invalidates `{ kind: "itinerary", id }` marks the entry `useItinerary` reads stale, and a
  // delete evicts the entry of what it deleted.
  const cache = useStudioCache(queryClient);
  const { bus, context, store } = useMemo(() => {
    const uiStore = createUiStore();
    // No `playbook`. It is the model-facing tool description the co-pilot reads, it is
    // optional, and this application has no co-pilot: passing it would pull
    // `@mountaya/studio/agent` into a bundle that renders a list of segments.
    const created = createStudioToolBus();

    const ctx: StudioToolContext = {
      // Where a handler writes, and what it makes stale afterwards: the API itself, through the
      // client the list reads with, and the cache the list reads from.
      api: {
        cache,
        client: mountaya,
        persistence: restStudioPersistence(mountaya),
      },
      // The bus's dispatch surface and nothing else of it, as the host hands it: a handler or a
      // plugin chains into another verb through it and can take none off.
      bus: created.dispatcher,
      capabilities: new Set(["authenticated", "editor"]),
      // The bus asks before a verb that destroys something runs, and refuses it where there is
      // nobody to ask. The one such verb this page dispatches is the delete, and the question
      // is this application's to word.
      confirm: async () => window.confirm("Delete this segment?"),
      map: null,
      saveFile: browserSaveFile,
      ui: uiStore,
      // The reader of this studio, as far as a handler asks: who they are, and nothing they are
      // entitled to beyond it. A host with accounts answers the other questions from its own.
      viewer: createStaticViewer({ getUserId: () => USER_ID }),
    };

    return { bus: created, context: ctx, store: uiStore };
  }, [cache, mountaya]);

  return (
    <MountayaStudioProvider client={mountaya} data={{ bus, context, store }}>
      {children}
    </MountayaStudioProvider>
  );
};

/** The itinerary, folded into the view shape the list reads. */
const Segments = () => {
  const { data } = useItinerary(ITINERARY_ID);

  if (data === undefined) {
    return <p>Loading…</p>;
  }

  return (
    <SegmentList
      itineraryId={ITINERARY_ID}
      segments={persistedItineraryView(data).source.segments}
    />
  );
};

/**
 * The application: one client for its life, built over `session`.
 *
 * The session names the member its writes act as, since a publishable key belongs to an
 * organization and the client refuses a write under a token minted for nobody. A request made
 * before the first token waits for it, so the list's first read is the draft's, and a refresh
 * rebuilds nothing.
 */
export const App = () => {
  const { session } = useSessionToken({ mint: mintSession });
  const [mountaya] = useState(
    () =>
      new Mountaya({
        credential: { publishableKey: PUBLISHABLE_KEY, sessionToken: session },
      }),
  );

  return (
    <QueryClientProvider client={queryClient}>
      <MountayaProvider client={mountaya}>
        <Wired>
          <Segments />
        </Wired>
      </MountayaProvider>
    </QueryClientProvider>
  );
};
From examples/studio-headless/src/SegmentList.tsx
import type { ItineraryViewSource } from "@mountaya/studio";
import { useSegmentList, useSegmentRow } from "@mountaya/studio-react/headless";

// Not one import from `@mountaya/studio-react` itself, and no stylesheet anywhere in this file.
// The verbs below (rename and delete) are the same ones Mountaya's own segment list dispatches;
// what is different is every line of the markup.

const Row = ({ itineraryId, name, segmentId }: SegmentRowProps) => {
  // The type argument is the seam: `rowProps.ref` is the row element the map's hover scrolls
  // into view, and naming `HTMLLIElement` here is what lets it hang on an `<li>`. It defaults to
  // `HTMLDivElement`, which is what Mountaya's own row renders, and a headless consumer whose
  // markup is not a div says so once.
  const row = useSegmentRow<HTMLLIElement>({ itineraryId, segmentId, segmentName: name });

  return (
    <li {...row.rowProps}>
      {row.rename.editing ? (
        <input {...row.rename.inputProps} />
      ) : (
        <button onDoubleClick={row.startRename} type="button">
          {name}
        </button>
      )}
      <button onClick={() => void row.actions.remove()} type="button">
        Delete
      </button>
      {row.actions.lastFailure === null ? null : (
        <span role="alert">Couldn't {row.actions.lastFailure.verb} this segment.</span>
      )}
    </li>
  );
};

interface SegmentRowProps {
  readonly itineraryId: string;
  readonly name: string;
  readonly segmentId: string;
}

export const SegmentList = ({
  itineraryId,
  segments,
}: {
  readonly itineraryId: string;
  readonly segments: ItineraryViewSource["segments"];
}) => {
  const list = useSegmentList({ itineraryId, segments });

  // `liveSegments` rather than `segments`: an edit in flight occupies a visual position without
  // occupying a chain one, so rendering the committed chain would drop the row being drawn.
  return (
    <ul>
      {list.liveSegments.map((segment) => (
        <Row
          itineraryId={itineraryId}
          key={segment.id}
          name={segment.name ?? "Untitled"}
          segmentId={segment.id}
        />
      ))}
    </ul>
  );
};

Run it

Replace pk_…, user_… and itin_… in src/App.tsx with a key carrying the studio-embedded scope, a member's id and an itinerary id. Serve /api/mountaya-session from your backend, as the studio quickstart shows. Drop the resolve.conditions from vite.config.ts: they build the example against the SDK's source in its repository.

npm install
npm run dev

The same app is examples/studio-headless in the SDK repository.

Next steps

Last updated