---
title: "Studio"
description: "Studio - build whole web apps visually from the system's components: the Visual Editor, every docs example as a library to drop from, pages, a selection tree, an inspector with each component's state, a live preview, and exports an agent can continue from."
slug: "studio"
---

import { DocPage, PageHeader, DocText, DocLink } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="studio" title="Studio" introStyle="max-width:44rem;">
  Rapid Agentic Development, the visual half: compose an app from the system's components, page by page, and hand it to an agent - or take what an agent wrote and finish it by hand. The library is every component of these docs alone - about 1,600 of them, cut from the examples - and every example, about 1,650, under the page that shows them, in the markup agents are told to write; the canvas is the <DocLink href="visual-editor.html">Visual Editor</DocLink>; the preview is the <DocLink href="code-example.html">HTML Preview Editor</DocLink>, running the page with every component it uses. Built only from shipped components.
</PageHeader>

<div class="flex flex-wrap items-center gap-2 mb-6">
  <a class="btn" href="full-studio.html" target="_blank" rel="noopener"><i data-lucide="maximize-2"></i> Open full screen</a>
  <a class="btn" data-variant="outline" href="#the-rad-loop">The RAD loop</a>
</div>

```html example standalone label="Studio" schema="none" sandbox="editor" height="50" mode="desktop" hint="A Border Layout of Panels: drag a divider to resize a side, double-click it (or the panel buttons in the toolbar) to fold it; minimize a panel to its title bar or maximize it over its column. West: the components and examples of the docs under their section and page - each component alone first, then the examples that compose it; pick one and it shows below as it will look on the page; drag it onto the page from the tree or from the preview, or click it to put it into or after the selected element. Center: the page. East: the selection - the path from the page down to it and everything inside it - its properties (the classes in a tag input of the system's classes), and the state of a component that has one. Preview runs the page; Export writes a page, the whole app as a ZIP, the project as JSON - or copies it for an agent. The work is kept in this browser."
<style>
  /* the Studio's own glue: sizes and the example previews. Every control is a shipped component (Border Layout,
     Panel, Toolbar, Button, Input, Select, Popover, Tree View, Property Grid, Tree Grid, Card, Dropdown, Badge)
     around the Visual Editor and the HTML Preview Editor */
  .studio {
    height: var(--scaffold-height, 50rem);
    background: var(--background);
    color: var(--foreground);
    font-size: 0.875rem;
  }
  /* the toolbar spans the north region (the region's divider is its edge) and wraps; its selects take their
     content's width (a .select fills its line by default) */
  .studio-bar {
    flex-wrap: wrap;
    width: auto;
    gap: 0.375rem;
    padding: 0.5rem 0.75rem;
    border: 0;
    border-radius: 0;
  }
  .studio-bar > .select {
    width: auto;
  }
  .studio-main {
    display: grid;
    padding: 0.75rem;
    background: var(--muted);
  }
  .studio-main > .visual-editor {
    --visual-editor-height: 100%;
  }
  .studio-main > .code-example {
    height: 100%;
    margin: 0;
  }
  /* the canvas or the preview: the card's own display would show a hidden one */
  .studio-main > [hidden] {
    display: none;
  }
  /* the side views are Panels: minimized to their title bar, maximized over their column. The library's search
     stays on top while the tree scrolls below it */
  .studio-library-body {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    padding: 0.5rem;
  }
  .studio-library-body > nav {
    flex: 1;
    min-height: 0;
    overflow: auto;
  }
  /* the selection tree and the state fit their content - Border Layout regions with data-fit; dense rows: the tree
     grid's row height is its documented custom property */
  .studio-state-body > [hidden] {
    display: none;
  }
  #studio-state {
    --data-grid-row-height: 28px;
    min-height: 0;
  }
  /* the class editor (a Combobox tag input) fills its cell: its field wraps the tags, never widens the table */
  #studio-props .combobox {
    inline-size: 100%;
    min-inline-size: 0;
  }
  #studio-props .combobox-field-input {
    min-inline-size: 3rem;
  }
  /* the HTML Preview Editor that runs the selected component (its State API, its render()) - out of sight */
  .studio-runner {
    position: absolute;
    inset-inline-start: -10000px;
    inset-block-start: 0;
    width: 960px;
    visibility: hidden;
  }
  /* the picked example: a static frame of its markup (styled, never run - as the canvas shows it), dragged by the
     grip laid over the frame or clicked as a whole. The grip, not the example, is draggable: WebKit cancels the drag
     of an element that holds an iframe (VERIFIED in Playwright's WebKit: tmp/probe-webkit-dnd.ts) */
  .studio-sample-body {
    scrollbar-gutter: stable;
  }
  .studio-sample {
    display: grid;
    gap: 0.25rem;
    margin-block-end: 0.75rem;
  }
  .studio-sample-grip {
    position: absolute;
    inset: 0;
    cursor: grab;
  }
  #studio-library [draggable='true'] {
    cursor: grab;
  }
  .studio-sample > .btn {
    justify-content: flex-start;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .studio-sample-view {
    position: relative;
    overflow: hidden;
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    background: var(--background);
  }
  .studio-sample:is(:hover, :focus-within) .studio-sample-view {
    border-color: var(--ring);
  }
  .studio-sample-frame {
    display: block;
    border: 0;
    transform-origin: 0 0;
    pointer-events: none;
  }
</style>
<div
  class="border-layout studio"
  id="studio"
  data-frame="none"
  data-center-min="320"
  data-collapsible
  data-save="studio-layout"
  data-density="compact"
>
  <header class="border-layout-north">
    <div class="toolbar studio-bar" role="toolbar" aria-label="Studio" data-size="sm">
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Components"
        aria-pressed="true"
        data-studio-fold="west"
      >
        <i data-lucide="panel-left"></i>
      </button>
      <strong>Studio</strong>
      <input
        class="input"
        data-size="sm"
        id="studio-name"
        aria-label="Project name"
        value="Untitled app"
        style="width: 10rem"
      />
      <select class="select" data-size="sm" id="studio-projects" aria-label="Open a project"></select>
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <select class="select" data-size="sm" id="studio-pages" aria-label="Page"></select>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Add a page"
        popovertarget="studio-add-page-pop"
      >
        <i data-lucide="file-plus"></i>
      </button>
      <div class="popover" id="studio-add-page-pop" popover>
        <form class="flex gap-1" id="studio-add-page">
          <input class="input" data-size="sm" name="name" placeholder="New page" aria-label="New page name" required />
          <button class="btn" data-size="sm" type="submit">Add</button>
        </form>
      </div>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Remove this page"
        id="studio-remove-page"
      >
        <i data-lucide="file-minus"></i>
      </button>
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Undo"
        data-visual-editor-for="studio-canvas"
        data-visual-editor-action="undo"
      >
        <i data-lucide="undo-2"></i>
      </button>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Redo"
        data-visual-editor-for="studio-canvas"
        data-visual-editor-action="redo"
      >
        <i data-lucide="redo-2"></i>
      </button>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Duplicate the selection"
        data-visual-editor-for="studio-canvas"
        data-visual-editor-action="duplicate"
      >
        <i data-lucide="copy"></i>
      </button>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Remove the selection"
        data-visual-editor-for="studio-canvas"
        data-visual-editor-action="remove"
      >
        <i data-lucide="trash-2"></i>
      </button>
      <select
        class="select"
        data-size="sm"
        aria-label="Device"
        data-visual-editor-for="studio-canvas"
        data-visual-editor-action="device"
      >
        <option value="desktop">Desktop</option>
        <option value="tablet">Tablet</option>
        <option value="phone">Phone</option>
      </select>
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <button
        class="btn"
        data-variant="outline"
        data-size="sm"
        type="button"
        id="studio-preview-toggle"
        aria-pressed="false"
      >
        <i data-lucide="play"></i> Preview
      </button>
      <button
        class="btn"
        data-size="sm"
        type="button"
        aria-haspopup="menu"
        aria-expanded="false"
        aria-controls="studio-export"
        data-dropdown-trigger="studio-export"
      >
        <i data-lucide="download"></i> Export
      </button>
      <div id="studio-export" role="menu" popover class="dropdown-content" aria-label="Export">
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="page"
          >This page as HTML</button
        >
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="zip"
          >The app as a ZIP</button
        >
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="json"
          >The project as JSON</button
        >
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="agent"
          >Copy for an agent</button
        >
        <div class="dropdown-separator" role="separator"></div>
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="open"
          >Open a project file...</button
        >
        <button role="menuitem" class="dropdown-item" tabindex="-1" type="button" data-export="new">New project</button>
      </div>
      <input type="file" id="studio-file" accept="application/json,.json" hidden />
      <span class="badge" data-variant="outline" id="studio-status" role="status">Ready</span>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-label="Inspector"
        aria-pressed="true"
        data-studio-fold="east"
        style="margin-inline-start: auto"
      >
        <i data-lucide="panel-right"></i>
      </button>
    </div>
  </header>
  <div class="resizer border-layout-west" data-min="200" data-max="520">
    <aside
      class="border-layout"
      data-frame="none"
      data-save="studio-library"
      style="width: 15rem"
      aria-label="Components"
    >
      <section
        class="card panel border-layout-center"
        id="studio-library-panel"
        data-density="compact"
        aria-labelledby="studio-library-title"
      >
        <header class="panel-header">
          <i data-lucide="book-open" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="studio-library-title">Components</h3>
          <div class="panel-tools">
            <label class="swap panel-maximize">
              <input type="checkbox" aria-label="Maximize Components" />
              <span class="swap-off"><i data-lucide="maximize-2"></i></span>
              <span class="swap-on"><i data-lucide="minimize-2"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body studio-library-body">
          <input
            class="input"
            data-size="sm"
            type="search"
            id="studio-search"
            placeholder="Search components"
            aria-label="Search components"
          />
          <nav id="studio-library" aria-label="Components by section and page" data-visual-editor-for="studio-canvas">
            <p class="text-muted-foreground">Loading the components...</p>
          </nav>
        </div>
      </section>
      <div class="resizer border-layout-south" data-min="96">
        <section
          class="card panel"
          id="studio-example-panel"
          data-density="compact"
          style="height: 16rem"
          aria-labelledby="studio-sample-title"
        >
          <header class="panel-header">
            <i data-lucide="eye" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="studio-sample-title">Example</h3>
            <div class="panel-tools">
              <label class="swap panel-maximize">
                <input type="checkbox" aria-label="Maximize Example" />
                <span class="swap-off"><i data-lucide="maximize-2"></i></span>
                <span class="swap-on"><i data-lucide="minimize-2"></i></span>
              </label>
              <label class="swap panel-minimize">
                <input type="checkbox" aria-label="Minimize Example" />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body studio-sample-body">
            <p class="text-muted-foreground mb-2">
              Pick a component or an example above - or drag it from the tree. Drag it onto the page, or click it to
              insert it at the selection.
            </p>
            <div id="studio-samples" data-visual-editor-for="studio-canvas" aria-label="The picked entry"></div>
          </div>
        </section>
      </div>
    </aside>
  </div>
  <main class="border-layout-center studio-main">
    <div class="visual-editor" id="studio-canvas" aria-label="The page">
      <script type="text/html" class="visual-editor-source">
        <main class="container stack gap-6" style="padding: 3rem 1.5rem">
          <section class="stack gap-3 items-start" style="max-width: 40rem">
            <span class="badge" data-variant="secondary">New</span>
            <h1 class="h1">Ship the app you sketched</h1>
            <p class="text-muted-foreground">Drop components from the library, change them in the inspector, preview, export.</p>
            <div class="flex gap-2"><button class="btn">Get started</button><button class="btn" data-variant="outline">Learn more</button></div>
          </section>
        </main>
      </script>
    </div>
    <div class="code-example" id="studio-preview" aria-label="Preview" hidden><textarea></textarea></div>
  </main>
  <div class="resizer border-layout-east" data-min="240" data-max="640">
    <aside class="border-layout" data-frame="none" style="width: 19rem" aria-label="Inspector">
      <section
        class="card panel border-layout-north"
        id="studio-selection-panel"
        data-fit
        data-density="compact"
        style="--border-layout-fit-min: 20cqh"
        aria-labelledby="studio-selection-title"
      >
        <header class="panel-header">
          <i data-lucide="layers" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="studio-selection-title">Selection</h3>
          <div class="panel-tools">
            <label class="swap panel-maximize">
              <input type="checkbox" aria-label="Maximize Selection" />
              <span class="swap-off"><i data-lucide="maximize-2"></i></span>
              <span class="swap-on"><i data-lucide="minimize-2"></i></span>
            </label>
            <label class="swap panel-minimize">
              <input type="checkbox" aria-label="Minimize Selection" />
              <span class="swap-off"><i data-lucide="chevron-up"></i></span>
              <span class="swap-on"><i data-lucide="chevron-down"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body"><div id="studio-tree"></div></div>
      </section>
      <div class="border-layout border-layout-center" data-frame="none">
        <section
          class="card panel border-layout-center"
          id="studio-props-panel"
          data-density="compact"
          aria-labelledby="studio-props-title"
        >
          <header class="panel-header">
            <i data-lucide="sliders-horizontal" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="studio-props-title">Properties</h3>
            <div class="panel-tools">
              <label class="swap panel-maximize">
                <input type="checkbox" aria-label="Maximize Properties" />
                <span class="swap-off"><i data-lucide="maximize-2"></i></span>
                <span class="swap-on"><i data-lucide="minimize-2"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body">
            <p class="text-muted-foreground mb-2" id="studio-inspect-hint">Select an element in the page.</p>
            <div class="property-grid" id="studio-props" aria-label="The selected element">
              <script type="application/json" class="property-grid-source">
                {}
              </script>
            </div>
          </div>
        </section>
        <section
          class="card panel border-layout-south"
          id="studio-state-panel"
          data-fit
          data-density="compact"
          aria-labelledby="studio-state-title"
        >
          <header class="panel-header">
            <i data-lucide="activity" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="studio-state-title">State</h3>
            <div class="panel-tools">
              <label class="swap panel-maximize">
                <input type="checkbox" aria-label="Maximize State" />
                <span class="swap-off"><i data-lucide="maximize-2"></i></span>
                <span class="swap-on"><i data-lucide="minimize-2"></i></span>
              </label>
              <label class="swap panel-minimize">
                <input type="checkbox" aria-label="Minimize State" />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body studio-state-body">
            <div
              class="data-grid"
              id="studio-state"
              aria-label="The state of the selected component"
              data-parent-field="parent"
              data-persist="none"
              hidden
            >
              <div class="data-grid-viewport">
                <div class="data-grid-head">
                  <div class="data-grid-row">
                    <div class="data-grid-header" data-field="name" data-width="9rem">State</div>
                    <div class="data-grid-header" data-field="value" data-width="8rem">Value</div>
                  </div>
                </div>
                <div class="data-grid-body"></div>
              </div>
            </div>
            <div class="card" id="studio-stateless" data-density="compact">
              <div class="card-header">
                <h4 class="card-title">No state</h4>
                <p class="card-description" id="studio-stateless-text">Select an element in the page.</p>
              </div>
            </div>
          </div>
        </section>
      </div>
    </aside>
  </div>
  <!-- the HTML Preview Editor that runs the selected component, out of sight - outside the panels, so a minimized
       State panel never hides it -->
  <div class="studio-runner" id="studio-runner" aria-hidden="true" inert></div>
</div>
<script>
  // ALPHA (2026-10-18): too fragile to offer yet - the docs do not list the Studio (nav.ts `alpha`)
  document.addEventListener('DOMContentLoaded', () => {
    const $ = df$;
    const ve = $.shadcn.visualEditor;
    const ce = $.shadcn.codeExample;
    const CANVAS = '#studio-canvas';
    const canvas = $(CANVAS).get(0);
    const START = $('#studio-canvas > script.visual-editor-source').text().trim();
    // the docs root: a page beside it says where it is (full-studio.html: data-docs-root="../"); a docs preview's base is it
    const docsRoot = new URL(document.documentElement.dataset.docsRoot ?? '', document.baseURI);
    const esc = (s) =>
      String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
    const slug = (s) =>
      String(s)
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '') || 'page';
    const status = (text) => $('#studio-status').text(text);
    // a Tree View branch row's chevron (the tree turns it when the branch opens)
    const CHEVRON =
      '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"></path></svg>';

    // ---- the frame: a Border Layout; the toolbar's panel buttons fold its sides (so does a double-click on a divider)
    const layout = $('#studio').get(0);
    const syncFolds = () =>
      ['west', 'east'].forEach((side) =>
        $(`[data-studio-fold="${side}"]`).attr(
          'aria-pressed',
          String(!$(layout).children(`.border-layout-${side}`).get(0)?.hasAttribute('data-collapsed')),
        ),
      );
    $('[data-studio-fold]').on('click', (e) =>
      $.shadcn.borderLayout.toggle(layout, e.currentTarget.dataset.studioFold),
    );
    $(layout).on('border-layout-collapse', syncFolds);
    syncFolds();
    // the side views are Panels: a minimized one stays minimized in this browser, as the sizes stay; a maximized one
    // comes back restored (it covers its column for a moment)
    const panels = $.store.persisted(
      'studio:panels',
      { minimized: [] },
      { validate: (v) => !!v && Array.isArray(v.minimized) && v.minimized.every((id) => typeof id === 'string') },
    );
    panels.value.minimized.forEach((id) => $.shadcn.panel.minimize(id));
    // State folds to its title bar while the selection has no state - the Studio's own fold, never remembered; a
    // panel the person minimized stays as they left it
    let folding = false;
    const foldState = (fold) => {
      const panel = $('#studio-state-panel').get(0);
      if (panels.value.minimized.includes(panel.id) || panel.hasAttribute('data-minimized') === fold) return;
      folding = true;
      if (fold) $.shadcn.panel.minimize(panel);
      else $.shadcn.panel.restore(panel);
      folding = false;
    };
    $(layout).on('panel-change', (e) => {
      if (folding) return;
      const id = e.target.id;
      const rest = panels.value.minimized.filter((x) => x !== id);
      if (id) panels.set({ minimized: e.detail.state === 'minimized' ? [...rest, id] : rest });
    });

    // ---- projects: kept in this browser (memory where it refuses storage - a sandboxed preview)
    let refused = false;
    const isProject = (p) =>
      !!p &&
      typeof p.id === 'string' &&
      typeof p.name === 'string' &&
      Array.isArray(p.pages) &&
      p.pages.length > 0 &&
      p.pages.every((g) => g && typeof g.id === 'string' && typeof g.name === 'string' && typeof g.html === 'string');
    const kept = $.store.persisted(
      'studio:projects',
      { current: '', list: [] },
      {
        validate: (v) =>
          !!v &&
          typeof v === 'object' &&
          typeof v.current === 'string' &&
          Array.isArray(v.list) &&
          v.list.every(isProject),
        onError: () => (refused = true),
      },
    );
    const fresh = (name, html = START) => ({
      id: `p-${Date.now().toString(36)}`,
      name,
      pages: [{ id: 'index', name: 'Home', html }],
    });
    let project = kept.value.list.find((p) => p.id === kept.value.current) ?? fresh('Untitled app');
    let page = project.pages[0];
    let ready = false;

    // the page: its markup, and the CSS the canvas keeps beside it - an example's <style> is applied there but moved
    // into rules, out of html(); setHtml() reads a <style> back. VERIFIED: tmp/probe-grapes-style.ts
    const pageMarkup = () => {
      const css = ve.css(CANVAS);
      return css ? `${ve.html(CANVAS)}\n<style>\n${css}\n</style>` : ve.html(CANVAS);
    };
    const keep = () => {
      if (ready) page.html = pageMarkup();
      project.name = String($('#studio-name').val() || 'Untitled app');
      const list = [project, ...kept.value.list.filter((p) => p.id !== project.id)];
      kept.set(JSON.parse(JSON.stringify({ current: project.id, list })));
      status(refused ? 'Kept in memory only' : 'Saved');
      renderProjects();
    };
    // a select's options are rewritten, then its value set: an option's selected attribute stops counting once
    // the user has picked one
    const renderProjects = () => {
      const list = kept.value.list.some((p) => p.id === project.id) ? kept.value.list : [project, ...kept.value.list];
      $('#studio-projects').html(list.map((p) => `<option value="${esc(p.id)}">${esc(p.name)}</option>`).join(''));
      $('#studio-projects').val(project.id);
    };
    const renderPages = () => {
      $('#studio-pages').html(
        project.pages.map((p) => `<option value="${esc(p.id)}">${esc(p.name)} (${esc(p.id)}.html)</option>`).join(''),
      );
      $('#studio-pages').val(page.id);
      $('#studio-remove-page').prop('disabled', project.pages.length < 2);
    };
    const showPage = (p) => {
      page = p;
      ve.setHtml(CANVAS, p.html);
      renderPages();
      lockStateful();
      renderSelection();
      inspect(null);
      loadState(null);
    };
    const openProject = (p) => {
      project = p;
      $('#studio-name').val(p.name);
      showPage(p.pages[0]);
      renderProjects();
    };

    // ---- "Open in Studio": a docs example arrives in the address fragment (#source=, deflate-raw + base64url)
    const handoff = async () => {
      const m = /[#&]source=([A-Za-z0-9_-]+)/.exec(location.hash);
      if (!m) return null;
      const bytes = Uint8Array.from(atob(m[1].replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
      const text = await new Response(
        new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw')),
      ).text();
      history.replaceState(null, '', location.pathname + location.search);
      return text;
    };

    const start = async () => {
      ready = true;
      const source = await handoff().catch(() => null);
      if (source !== null) {
        openProject(fresh('From the docs', source));
        keep();
        status('Opened from the docs');
      } else openProject(project);
    };
    if (canvas.hasAttribute('data-ready')) start();
    else $(canvas).on('visual-editor-ready', start);

    let timer;
    $(canvas).on('visual-editor-change', () => {
      status('Editing...');
      lockStateful();
      renderSelection();
      clearTimeout(timer);
      timer = setTimeout(keep, 500);
    });
    $('#studio-name').on('change', keep);
    $('#studio-projects').on('change', (e) => {
      keep();
      const next = kept.value.list.find((p) => p.id === e.target.value);
      if (next) openProject(next);
    });
    $('#studio-pages').on('change', (e) => {
      keep();
      const next = project.pages.find((p) => p.id === e.target.value);
      if (next) showPage(next);
    });
    $('#studio-remove-page').on('click', () => {
      if (project.pages.length < 2) return;
      project.pages = project.pages.filter((p) => p !== page);
      showPage(project.pages[0]);
      keep();
    });
    $('#studio-add-page').on('submit', (e) => {
      e.preventDefault();
      keep();
      const name = String(new FormData(e.target).get('name') ?? '').trim() || 'Page';
      let id = slug(name);
      for (let n = 2; project.pages.some((p) => p.id === id); n++) id = `${slug(name)}-${n}`;
      const next = {
        id,
        name,
        html: `<main class="container stack gap-4" style="padding: 3rem 1.5rem"><h1 class="h1">${esc(name)}</h1><p class="text-muted-foreground">A new page.</p></main>`,
      };
      project.pages.push(next);
      e.target.reset();
      $('#studio-add-page-pop').get(0).hidePopover();
      showPage(next);
      keep();
    });

    // ---- trees: a Tree View is written whole, its container emptied first - df$'s morph would keep the old <ul>
    // and its listeners, and Tree View would bind it a second time
    const fill = (target, markup) => {
      $(target).html('');
      $(target).html(markup);
    };
    // a row's icon: the inner markup of a 24 × 24 lucide SVG - a section's is its sidebar icon (library.json)
    const icon = (body) =>
      body
        ? `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`
        : '';
    // lucide's box (a component alone) and layout-template (an example that composes it)
    const PART =
      '<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/>';
    const EXAMPLE =
      '<rect width="18" height="7" x="3" y="3" rx="1"/><rect width="9" height="7" x="3" y="14" rx="1"/><rect width="5" height="7" x="16" y="14" rx="1"/>';
    const branch = (label, open, kids, attrs = '', glyph = '') =>
      `<li class="tree-item" role="treeitem" aria-expanded="${open}"${attrs}><details class="tree-branch"${open ? ' open' : ''}><summary class="tree-branch-trigger">${CHEVRON}${icon(glyph)}<span>${esc(label)}</span></summary><ul class="tree-group" role="group">${kids}</ul></details></li>`;
    const leaf = (label, attrs, row = '', glyph = '') =>
      `<li class="tree-item" role="treeitem"${attrs}><span class="tree-leaf" tabindex="0" title="${esc(label)}"${row}>${icon(glyph)}<span>${esc(label)}</span></span></li>`;

    // ---- the selection (east, north): the path from the page down to the selected element - highlighted - and
    // every element inside it, down to the deepest; nothing selected = the whole page. A row selects its element.
    // The region takes the height the tree needs (a Border Layout data-fit region), a fifth to half of the inspector
    const renderSelection = () => {
      const path = ve.selection(CANVAS)?.path ?? null;
      const steps = path === null ? [] : path.split('.').map((_, i, all) => all.slice(0, i + 1).join('.'));
      const row = (n, kids, selected) =>
        kids.length
          ? branch(n.label, true, kids.join(''), ` aria-selected="${selected}" data-path="${n.path}"`)
          : leaf(n.label, ` aria-selected="${selected}" data-path="${n.path}"`);
      const whole = (n) => row(n, n.children.map(whole), n.path === path);
      const along = (level, i) => {
        const n = level.find((x) => x.path === steps[i]);
        if (!n) return '';
        return i === steps.length - 1 ? whole(n) : row(n, [along(n.children, i + 1)], false);
      };
      const outline = ve.outline(CANVAS);
      const inside = path === null ? outline.map(whole) : [along(outline, 0)];
      const focused = $('#studio-tree').get(0).contains(document.activeElement);
      fill(
        '#studio-tree',
        `<ul class="tree" role="tree" aria-label="The selection in the page" data-selectable data-variant="guides" data-density="compact">${branch('Page', true, inside.join(''), ` aria-selected="${path === null}" data-path=""`)}</ul>`,
      );
      // the row a key or a click chose keeps the focus across the redraw
      if (focused)
        $('#studio-tree [aria-selected="true"]')
          .find(':scope > details > summary, :scope > .tree-leaf')
          .get(0)
          ?.focus();
    };
    $('#studio-tree').on('tree-select', (e) => {
      const p = e.detail.item.dataset.path;
      ve.select(CANVAS, p ? p : null);
    });

    // ---- components with state: a component with a script renders its markup from its state (render()), so in the
    // page it is one locked unit (lock(): nothing in it is edited, moved or removed, nothing drops into it) and it
    // changes through its state; markup without one is edited element by element, in the Property Grid
    let library = null;
    const owners = new Map(); // class → the component that owns it (library.components[].classes)
    const ownerOf = (el) => {
      for (let e = el; e && e.classList; e = e.parentElement)
        for (const c of e.classList) if (owners.has(c)) return owners.get(c);
      return null;
    };
    const statefulOf = (el) => {
      for (const c of el.classList) if (owners.get(c)?.js) return owners.get(c);
      return null;
    };
    // the page as the canvas holds it, parsed: element paths are the outline's (element children, by index)
    const parsedPage = () => new DOMParser().parseFromString(`<body>${ve.html(CANVAS)}</body>`, 'text/html').body;
    const at = (body, path) => path.split('.').reduce((el, i) => el?.children[Number(i)], body);
    const outer = (el) => $('<div></div>').append(el.cloneNode(true)).html();
    const lockStateful = () => {
      if (!library) return;
      const walk = (el, path) => {
        if (statefulOf(el)) ve.lock(CANVAS, path);
        else [...el.children].forEach((k, i) => walk(k, `${path}.${i}`));
      };
      [...parsedPage().children].forEach((k, i) => walk(k, String(i)));
    };

    // ---- the inspector (east, center north): the selection as one JSON object in the Property Grid; an edit is an
    // apply(). A locked unit's elements show read only - their markup is their component's render()
    const props = $('#studio-props').get(0);
    // the class property edits in a Combobox tag input: the classes on the element first (their order), then the
    // ones its component owns, then the system's utility classes by module (library.json); a class no list holds is
    // created as it is typed. Enter adds a tag (the editor owns it); Tab, or leaving the editor, writes the classes.
    // The first Escape closes an open list, the next one cancels the edit
    let inspected = null; // the selection the grid shows
    const classEditor = (value) => {
      const on = String(value ?? '')
        .split(/\s+/)
        .filter(Boolean);
      const component = inspected && ownerOf(at(parsedPage(), inspected.path));
      const groups = [
        { group: 'On this element', classes: on },
        ...(component ? [{ group: component.title, classes: component.classes }] : []),
        ...(library?.utilities ?? []),
      ];
      const listed = new Set();
      let n = 0;
      const rows = groups
        .map(({ group, classes }) => {
          const fresh = classes.filter((c) => !listed.has(c));
          fresh.forEach((c) => listed.add(c));
          if (!fresh.length) return '';
          const options = fresh
            .map(
              (c) =>
                `<div role="option" class="combobox-item" id="studio-class-${n++}" data-value="${esc(c)}" aria-selected="${on.includes(c)}">${esc(c)}</div>`,
            )
            .join('');
          return `<div class="combobox-group-label">${esc(group)}</div>${options}`;
        })
        .join('');
      const el = $(
        `<div class="combobox" id="studio-classes" data-multiple data-tags data-creatable data-size="sm"><div class="combobox-field"><input class="combobox-field-input" id="studio-classes-input" type="text" role="combobox" autocomplete="off" aria-expanded="false" aria-controls="studio-classes-list" aria-autocomplete="list" aria-label="Classes" placeholder="Add a class..."></div><div id="studio-classes-pop" class="combobox-content" popover="manual"><div id="studio-classes-list" role="listbox" class="combobox-listbox" aria-label="Classes"><div class="combobox-empty" hidden>No class matches.</div>${rows}</div></div></div>`,
      ).get(0);
      el.addEventListener(
        'keydown',
        (e) => {
          const list = $(el).find('.combobox-content').get(0);
          if (e.key !== 'Escape' || !list?.matches(':popover-open')) return;
          e.preventDefault();
          e.stopPropagation();
          list.api?.setState('default');
        },
        true,
      );
      return {
        el,
        ownsEnter: true,
        focus: () => $(el).find('.combobox-field-input').get(0)?.focus(),
        getValue: () =>
          $(el)
            .find('[role="option"][aria-selected="true"]')
            .toArray()
            .map((o) => o.dataset.value)
            .join(' '),
      };
    };
    $.shadcn.propertyGrid.configure(props, {
      getEditorFn: (key, value) => (key === 'class' ? classEditor(value) : null),
    });
    function inspect(s) {
      inspected = s;
      const locked = !!s?.unit;
      $('#studio-inspect-hint').text(
        !s
          ? 'Select an element in the page.'
          : locked
            ? `<${s.tag}> at ${s.path} - its component has state: change it below`
            : `<${s.tag}> at ${s.path}`,
      );
      const rest = s ? Object.fromEntries(Object.entries(s.attributes).filter(([k]) => k !== 'id')) : {};
      const source = s
        ? {
            element: s.tag,
            id: s.attributes.id ?? '',
            class: s.classes.join(' '),
            ...(s.text !== null ? { text: s.text } : {}),
            ...rest,
          }
        : {};
      const sourceConfig = Object.fromEntries(
        Object.keys(source).map((k) => [k, { readOnly: locked || k === 'element' }]),
      );
      $.shadcn.propertyGrid.configure(props, { source, sourceConfig });
    }
    $(props).on('property-grid-change', (e) => {
      const { key, value } = e.detail;
      try {
        if (key === 'class') ve.apply(CANVAS, { classes: String(value).split(/\s+/).filter(Boolean) });
        else if (key === 'text') ve.apply(CANVAS, { text: String(value) });
        else ve.apply(CANVAS, { attributes: { [key]: value === '' || value === null ? null : String(value) } });
      } catch (err) {
        status(err.message);
      }
    });

    // ---- the state (east, center): the selected unit's states in a Tree Grid - the HTML Preview Editor's State tab
    // (its schema, its controls' values). A hidden HTML Preview Editor runs the unit's markup with the component's
    // script; a value is set there the way the State tab sets it (setPreviewState), and the unit's new markup is what
    // the component's render() gives for the state it landed in - never the live DOM, which carries what the
    // runtime adds (data-init, its ARIA wiring) and would not start again. VERIFIED: tmp/probe-state-source.ts
    const grid = $('#studio-state').get(0);
    let unit = null; // { path, html, source, component, schema, card }
    let replacing = false;
    const camel = (n) => n.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    // a component without a schema: its State API's states, set by name (the State tab's '*' mutation)
    const schemaOf = (c) =>
      c.schema ?? {
        schemaVersion: 1,
        name: c.name,
        states: {
          state: {
            type: 'enum',
            values: $.shadcn[`${camel(c.name)}States`] ?? ['default'],
            default: 'default',
            target: { kind: 'root' },
            mutation: { kind: 'api', name: '*' },
            observation: { kind: 'api', name: '@state' },
          },
        },
      };
    const until = async (test, ms) => {
      for (const end = Date.now() + ms; Date.now() < end; await new Promise((r) => setTimeout(r, 50)))
        if (test()) return true;
      return test();
    };
    const frameOf = (card) => $(card).find('iframe.code-example-frame').get(0);
    const stateless = (text) => {
      unit = null;
      $('#studio-state-title').text('State: none');
      $(grid).prop('hidden', true);
      $('#studio-stateless').prop('hidden', false);
      $('#studio-stateless-text').text(text);
      foldState(true);
    };
    const valueCell = (el, r) => {
      if (r.kind === 'unit') return void $(el).text(r.value ? `state: ${r.value}` : '');
      const key = esc(r.name);
      const named = `data-state-key="${key}" aria-label="${key}"`;
      if (r.kind === 'boolean')
        $(el).html(`<input type="checkbox" class="checkbox" ${named}${r.value === true ? ' checked' : ''}>`);
      else if (r.kind === 'enum')
        $(el).html(
          `<select class="select" data-size="sm" ${named}>${(r.values ?? [])
            .map((v) => `<option${String(v) === String(r.value) ? ' selected' : ''}>${esc(v)}</option>`)
            .join('')}</select>`,
        );
      else
        $(el).html(
          `<input class="input" data-size="sm" type="${r.kind === 'number' ? 'number' : 'text'}" ${named} value="${esc(r.value ?? '')}">`,
        );
    };
    const showUnit = () => {
      const { card, schema, component } = unit;
      const observed = ce.previewState(card);
      const root = $(frameOf(card)?.contentDocument?.body).find('[data-studio-n="0"]').get(0);
      $('#studio-state-title').text(`State: ${component.title}`);
      foldState(false);
      $('#studio-stateless').prop('hidden', true);
      $(grid).prop('hidden', false);
      $.shadcn.dataGrid.setSource(
        grid,
        [
          { id: 'unit', parent: null, name: component.title, kind: 'unit', value: root?.api?.getState?.().name ?? '' },
          ...Object.entries(schema.states).map(([key, spec]) => ({
            id: `state:${key}`,
            parent: 'unit',
            name: key,
            kind: spec.type,
            values: spec.values ?? null,
            value: observed[key] ?? spec.default ?? null,
          })),
        ],
        { parentIdField: 'parent', cells: { value: valueCell } },
      );
      $.shadcn.dataGrid.expandAll(grid);
    };
    // the unit runs in the hidden HTML Preview Editor, every element numbered (data-studio-n) so its render() finds
    // its place in the markup again
    const loadUnit = async (path) => {
      const el = at(parsedPage(), path);
      const component = el && statefulOf(el);
      if (!component) return stateless('Select an element in the page.');
      const html = outer(el);
      if (unit?.card && unit.path === path && unit.html === html) return showUnit();
      const copy = el.cloneNode(true);
      [copy, ...copy.querySelectorAll('*')].forEach((e, i) => e.setAttribute('data-studio-n', String(i)));
      const mine = { path, html, source: outer(copy), component, schema: schemaOf(component), card: null };
      unit = mine;
      $('#studio-state-title').text(`State: ${component.title} (starting...)`);
      foldState(false);
      fill(
        '#studio-runner',
        `<div class="code-example" data-sandbox="editor" data-schema="${esc(JSON.stringify(mine.schema))}" aria-label="${esc(component.title)}, running"><textarea></textarea></div>`,
      );
      const card = $('#studio-runner > .code-example').get(0);
      await until(() => card.hasAttribute('data-init'), 3000);
      ce.setSource(card, mine.source);
      const started = await until(() => unit !== mine || Object.keys(ce.previewState(card)).length > 0, 15000);
      if (unit !== mine) return;
      if (!started) return stateless(`${component.title} did not start here - its state cannot be read.`);
      mine.card = card;
      showUnit();
    };
    // the unit's markup now: as written, every element with a State API replaced by what its render() gives for the
    // state it is in - outer ones first, the ones inside them after (their numbers find them in the outer render) -
    // and a form field's live value written as its attributes, as the State tab writes it into its source (a value is
    // a property: render() keeps the authored attribute)
    const rendered = (mine) => {
      const live = frameOf(mine.card).contentDocument;
      const out = new DOMParser().parseFromString(`<body>${mine.source}</body>`, 'text/html').body;
      const twinOf = (el) =>
        $(out)
          .find(`[data-studio-n="${el.getAttribute('data-studio-n')}"]`)
          .get(0);
      const bound = $(live.body).find('[data-studio-n]').toArray();
      for (const el of bound) {
        if (typeof el.api?.render !== 'function') continue;
        const twin = twinOf(el);
        const next = new DOMParser().parseFromString(`<body>${el.api.render()}</body>`, 'text/html').body
          .firstElementChild;
        if (twin && next) twin.replaceWith(next);
      }
      for (const el of bound) {
        const twin = /^(INPUT|TEXTAREA)$/.test(el.tagName) && twinOf(el);
        if (!twin) continue;
        if (el.type === 'checkbox' || el.type === 'radio') twin.toggleAttribute('checked', el.checked);
        else if (el.tagName === 'TEXTAREA') twin.textContent = el.value;
        else twin.setAttribute('value', el.value);
      }
      $(out)
        .find('[data-studio-n]')
        .toArray()
        .forEach((e) => e.removeAttribute('data-studio-n'));
      return $(out).html().trim();
    };
    // the bridge's next report (data-state-values): the state as it landed - where it was asked to, or elsewhere
    const reported = (card) =>
      new Promise((done) => {
        const watch = new MutationObserver(() => (watch.disconnect(), done(true)));
        watch.observe(card, { attributes: true, attributeFilter: ['data-state-values'] });
        setTimeout(() => (watch.disconnect(), done(false)), 1500);
      });
    const setUnitState = async (key, value) => {
      const mine = unit;
      if (!mine?.card) return;
      const report = reported(mine.card);
      ce.setPreviewState(mine.card, key, value);
      await report;
      // an async state (a chart mounting) finishes its DOM work first
      const live = $(frameOf(mine.card)?.contentDocument?.body).find('[data-studio-n]').toArray();
      await Promise.all(live.map((el) => el.api?.settled?.()));
      if (unit !== mine) return;
      replacing = true;
      ve.select(CANVAS, mine.path);
      const next = ve.replace(CANVAS, rendered(mine));
      replacing = false;
      if (!next) return status(`${mine.component.title} could not be replaced`);
      mine.html = outer(at(parsedPage(), mine.path));
      status(`${mine.component.title}: ${key} = ${ce.previewState(mine.card)[key] ?? value}`);
      inspect(next);
      renderSelection();
      showUnit();
    };
    $(grid).on('change', (e) => {
      const control = e.target.closest('[data-state-key]');
      if (!control || !unit) return;
      const spec = unit.schema.states[control.dataset.stateKey];
      const value =
        control.type === 'checkbox' ? control.checked : spec?.type === 'number' ? Number(control.value) : control.value;
      setUnitState(control.dataset.stateKey, value);
    });
    const loadState = (s) => {
      if (!s) return stateless('Select an element in the page.');
      if (s.unit !== null) return loadUnit(s.unit);
      const c = ownerOf(at(parsedPage(), s.path));
      stateless(
        c
          ? `${c.title} has no state: its markup is edited directly, element by element, in the properties above.`
          : `<${s.tag}> belongs to no component with state: its markup is edited directly, in the properties above.`,
      );
    };
    $(canvas).on('visual-editor-select', () => {
      if (replacing) return;
      // a component dropped a moment ago may not be locked yet - the selection's unit says it is
      lockStateful();
      const s = ve.selection(CANVAS);
      inspect(s);
      renderSelection();
      loadState(s);
    });

    // ---- the library (west): the docs' components and examples by section and page (studio/library.json) - on a
    // page first its individual examples (each component alone - its parts file, then the page's own), then its
    // composite ones, as the page orders them. A page's markup comes when one of its entries is picked (studio/examples/<slug>.json). The entry shows
    // below the tree in a frame of its own: the page's stylesheets, no script - its markup as the canvas will show it.
    // One on the page of an organism, a block or a template is laid out at a desktop width and scaled down; any other
    // at the pane's width, scaled only when it is wider. Ids: "<slug>#<n>"
    let shown = '';
    const pages = new Map();
    const examples = new Map(); // slug → Promise of [{ label, html, individual }]
    const WIDE = new Set(['ORG', 'BLK', 'TPL']);
    const holdsShown = (p) => shown.split('#')[0] === p.slug || p.pages.some(holdsShown);
    // an entry of a page (labels: the page in library.json; markup: its file) by the key after '#'
    const entryOf = (list, key) => list?.[Number(key)];
    const renderLibrary = () => {
      if (!library) return;
      const words = String($('#studio-search').val() ?? '')
        .toLowerCase()
        .split(/\s+/)
        .filter(Boolean);
      const node = (p, trail) => {
        const context = `${trail} ${p.title}`.toLowerCase();
        // an individual example (one component alone) carries the box icon and data-individual, a composite the layout one
        const leaves = p.examples
          .map((label, i) => ({ label, id: `${p.slug}#${i}`, individual: p.individual.includes(i) }))
          .filter((x) => words.every((w) => `${context} ${x.label.toLowerCase()}`.includes(w)))
          .map((x) =>
            leaf(
              x.label,
              ` data-example="${esc(x.id)}" aria-selected="${x.id === shown}"${x.individual ? ' data-individual' : ''}`,
              ' draggable="true"',
              x.individual ? PART : EXAMPLE,
            ),
          );
        const subs = p.pages.map((q) => node(q, context)).filter(Boolean);
        if (!leaves.length && !subs.length) return '';
        return branch(
          p.title,
          words.length > 0 || holdsShown(p),
          [...leaves, ...subs].join(''),
          ` data-page="${esc(p.slug)}"`,
        );
      };
      const sections = library.sections
        .map((s) => {
          const kids = s.pages.map((p) => node(p, s.heading)).filter(Boolean);
          const open = words.length > 0 || s.pages.some(holdsShown);
          return kids.length ? branch(s.heading, open, kids.join(''), '', s.icon) : '';
        })
        .join('');
      fill(
        '#studio-library',
        sections
          ? `<ul class="tree" role="tree" aria-label="Components" data-selectable data-variant="guides" data-density="compact">${sections}</ul>`
          : '<p class="text-muted-foreground">Nothing matches.</p>',
      );
    };
    // the page's stylesheets (the frames' and the preview's): where each was loaded from, GrapesJS's own left out
    const sheetLinks = () =>
      $('link[rel="stylesheet"]')
        .toArray()
        .filter((l) => !l.hasAttribute('data-visual-editor-vendor'))
        .map((l) => $.shadcn.shared.sheetUrl(l))
        .filter(Boolean);
    const sheets = () => ({
      links: sheetLinks(),
      css: $('style')
        .toArray()
        .map((s) => s.textContent)
        .join('\n')
        .replace(/<\/style/gi, '<\\/style'),
    });
    const fit = (frame) => {
      const view = frame.parentElement;
      const doc = frame.contentDocument;
      const root = doc?.body?.firstElementChild;
      const w = view?.clientWidth ?? 0;
      if (!root || !w) return;
      frame.style.width = `${w}px`;
      const design = frame.closest('[data-wide]')
        ? Math.max(w, 1024)
        : Math.max(w, Math.min(doc.documentElement.scrollWidth, 1280));
      const scale = w / design;
      frame.style.width = `${design}px`;
      frame.style.scale = String(scale);
      const h = Math.max(Math.ceil(root.getBoundingClientRect().height), 40);
      frame.style.height = `${h}px`;
      view.style.height = `${Math.ceil(h * scale)}px`;
    };
    const paint = (frame, html) => {
      const { links, css } = sheets();
      const dark = document.documentElement.classList.contains('dark') ? ' class="dark"' : '';
      frame.onload = () => fit(frame);
      frame.srcdoc = `<!doctype html><html lang="en"${dark}><head><meta charset="utf-8"><base href="${esc(docsRoot.href)}">${links
        .map((h) => `<link rel="stylesheet" href="${esc(h)}">`)
        .join(
          '',
        )}<style>${css}</style><style>html,body{margin:0;background:var(--background);color:var(--foreground)}</style></head><body><div style="display:flow-root;padding:0.75rem">${html}</div></body></html>`;
    };
    const loaded = new Map(); // slug → [{ label, html, individual }], once its file arrived (a drag needs it at once)
    const examplesOf = (slug) => {
      if (!examples.has(slug))
        examples.set(
          slug,
          fetch(new URL(`studio/examples/${slug}.json`, docsRoot))
            .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
            .then((list) => (loaded.set(slug, list), list)),
        );
      return examples.get(slug);
    };
    const showExample = async (id) => {
      const [slug, n] = id.split('#');
      const p = pages.get(slug);
      if (!p) return;
      shown = id;
      $('#studio-sample-title').text(`${p.title}: ${p.examples[Number(n)]}`);
      const list = await examplesOf(slug).catch(() => {
        examples.delete(slug);
        return null;
      });
      if (shown !== id) return; // another pick came first
      const example = entryOf(list, n);
      if (!example)
        return void $('#studio-samples').html('<p class="text-muted-foreground">It could not be loaded.</p>');
      // the block is the whole example (a click anywhere inserts it); the grip over the frame drags it
      $('#studio-samples').html(
        `<div class="studio-sample" data-visual-editor-block${WIDE.has(p.type) ? ' data-wide' : ''}><button type="button" class="btn" data-variant="ghost" data-size="sm" title="Insert at the selection">${esc(example.label)}</button><div class="studio-sample-view"><iframe class="studio-sample-frame" sandbox="allow-same-origin" tabindex="-1" aria-hidden="true" title="${esc(example.label)}"></iframe><div class="studio-sample-grip" draggable="true" title="Drag onto the page - or click to insert at the selection"></div></div><script type="text/html">${example.html}<\/script></div>`,
      );
      paint($('#studio-samples .studio-sample-frame').get(0), example.html);
    };
    // a divider moved: the frame takes the pane's new width (only a width change - a height follows from it)
    let width = 0;
    new ResizeObserver(([entry]) => {
      if (Math.round(entry.contentRect.width) === width) return;
      width = Math.round(entry.contentRect.width);
      $('#studio-samples .studio-sample-frame').toArray().forEach(fit);
    }).observe($('#studio-samples').get(0));
    // the theme's dark mode reaches the frame
    new MutationObserver(() =>
      $('#studio-samples .studio-sample-frame')
        .toArray()
        .forEach((f) =>
          f.contentDocument?.documentElement.classList.toggle(
            'dark',
            document.documentElement.classList.contains('dark'),
          ),
        ),
    ).observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
    fetch(new URL('studio/library.json', docsRoot))
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
      .then((l) => {
        library = l;
        for (const c of l.components) for (const k of c.classes) owners.set(k, c);
        const index = (p) => {
          pages.set(p.slug, p);
          p.pages.forEach(index);
        };
        l.sections.forEach((s) => s.pages.forEach(index));
        renderLibrary();
        if (ready) lockStateful();
      })
      .catch(() => $('#studio-library').html('<p class="text-muted-foreground">The library could not be loaded.</p>'));
    let searching;
    $('#studio-search').on('input', () => {
      clearTimeout(searching);
      searching = setTimeout(renderLibrary, 150);
    });
    $('#studio-library').on('tree-select', (e) => {
      const id = e.detail.item.dataset.example;
      if (id) showExample(id);
    });
    // an example drags straight from the tree: its page's examples load when the pointer comes over it, and for the
    // drag the row becomes a Visual Editor block - data-visual-editor-block and the markup in a data block - which the
    // editor's own dragstart (on the document, after this one) takes into the canvas
    const exampleOf = (row) => {
      const [slug, n] = row.dataset.example.split('#');
      return entryOf(loaded.get(slug), n) ?? null;
    };
    $('#studio-library').on('pointerover', (e) => {
      const row = e.target.closest?.('[data-example]');
      if (row) examplesOf(row.dataset.example.split('#')[0]).catch(() => {});
    });
    $('#studio-library').on('dragstart', (e) => {
      const row = e.target.closest?.('[data-example]');
      if (!row) return;
      const example = exampleOf(row);
      if (!example) {
        e.preventDefault();
        return void status('The example is still loading - drag it again');
      }
      const data = document.createElement('script');
      data.type = 'text/html';
      data.textContent = example.html;
      $(row).attr('data-visual-editor-block', '').append(data);
    });
    // the editor ends its drag on the same event, after this one: the row stops being a block once it has
    $('#studio-library').on('dragend', (e) => {
      const row = e.target.closest?.('[data-visual-editor-block]');
      if (row)
        setTimeout(() => {
          $(row).attr('data-visual-editor-block', null);
          $(row).children('script[type="text/html"]').remove();
        });
    });

    // ---- preview: the page in the HTML Preview Editor. On a page that loads the bundles (full screen), the preview
    // takes all.* and the extra bundles the page uses from beside them; a docs preview hands its own down
    const preview = $('#studio-preview').get(0);
    const allJs = $('script[src*="components/all"]').get(0);
    if (allJs) {
      const base = new URL('.', allJs.src);
      ce.configure({
        styles: (src) => [...sheetLinks(), ...ce.bundlesFor(src).map((b) => new URL(`${b}.min.css`, base).href)],
        scripts: (src) => [
          new URL('all.min.js', base).href,
          ...ce.bundlesFor(src).map((b) => new URL(`${b}.min.js`, base).href),
        ],
      });
    }
    $('#studio-preview-toggle').on('click', (e) => {
      const on = e.currentTarget.getAttribute('aria-pressed') !== 'true';
      $(e.currentTarget).attr('aria-pressed', String(on));
      $(canvas).prop('hidden', on);
      $(preview).prop('hidden', !on);
      if (on) ce.setSource(preview, pageMarkup());
    });

    // ---- export: a page, the app as a ZIP (stored entries + CRC-32 - no library), the project, a hand-off for an agent
    const cdn = () =>
      `https://cdn.jsdelivr.net/gh/kyr0/defuss-shadcn@v${library?.version ?? 'latest'}/dist/components/`;
    const pageDocument = (p) => {
      const extra = ce.bundlesFor(p.html);
      const links = ['core', 'all', ...extra]
        .map((b) => `<link rel="stylesheet" href="${cdn()}${b}.min.css">`)
        .join('\n');
      const scripts = ['all', ...extra]
        .map((b) => `<script type="module" src="${cdn()}${b}.min.js"><\/script>`)
        .join('\n');
      return `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>${esc(p.name)} - ${esc(project.name)}</title>\n${links}\n</head>\n<body>\n${p.html}\n${scripts}\n</body>\n</html>\n`;
    };
    const save = (name, blob) => {
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = name;
      a.click();
      setTimeout(() => URL.revokeObjectURL(a.href), 1000);
    };
    const CRC = Array.from({ length: 256 }, (_, n) => {
      let c = n;
      for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
      return c >>> 0;
    });
    const crc32 = (bytes) => {
      let c = 0xffffffff;
      for (const b of bytes) c = CRC[(c ^ b) & 255] ^ (c >>> 8);
      return (c ^ 0xffffffff) >>> 0;
    };
    const zip = (files) => {
      const enc = new TextEncoder();
      const parts = [];
      const dir = [];
      let offset = 0;
      for (const f of files) {
        const name = enc.encode(f.name);
        const data = enc.encode(f.text);
        const crc = crc32(data);
        const head = new DataView(new ArrayBuffer(30));
        [
          [0, 0x04034b50, 4],
          [4, 20, 2],
          [6, 0x0800, 2],
          [14, crc, 4],
          [18, data.length, 4],
          [22, data.length, 4],
          [26, name.length, 2],
        ].forEach(([at, v, n]) => (n === 4 ? head.setUint32(at, v, true) : head.setUint16(at, v, true)));
        const cen = new DataView(new ArrayBuffer(46));
        [
          [0, 0x02014b50, 4],
          [4, 20, 2],
          [6, 20, 2],
          [8, 0x0800, 2],
          [16, crc, 4],
          [20, data.length, 4],
          [24, data.length, 4],
          [28, name.length, 2],
          [42, offset, 4],
        ].forEach(([at, v, n]) => (n === 4 ? cen.setUint32(at, v, true) : cen.setUint16(at, v, true)));
        parts.push(head, name, data);
        dir.push(cen, name);
        offset += 30 + name.length + data.length;
      }
      const size = dir.reduce((n, p) => n + p.byteLength, 0);
      const end = new DataView(new ArrayBuffer(22));
      [
        [0, 0x06054b50, 4],
        [8, files.length, 2],
        [10, files.length, 2],
        [12, size, 4],
        [16, offset, 4],
      ].forEach(([at, v, n]) => (n === 4 ? end.setUint32(at, v, true) : end.setUint16(at, v, true)));
      return new Blob([...parts, ...dir, end], { type: 'application/zip' });
    };
    const components = () => {
      const html = project.pages.map((p) => p.html).join('\n');
      const used = new Set([...html.matchAll(/class="([^"]*)"/g)].flatMap((m) => m[1].split(/\s+/)));
      return (library?.components ?? []).filter((c) => c.classes.some((k) => used.has(k)));
    };
    const agentNotes = () =>
      [
        `# ${project.name}`,
        '',
        `Built in the defuss-shadcn Studio (v${library?.version ?? ''}) from shipped components only - keep it that way: read each skill before changing its markup.`,
        '',
        '## Components and their skills',
        '',
        ...components().map((c) => `- ${c.title} (\`${c.name}\`): ${library.skills}${c.name}/component-skill.md`),
        '',
        ...project.pages.flatMap((p) => [
          `## Page: ${p.name} (\`${p.id}.html\`)`,
          '',
          '```html',
          p.html.trim(),
          '```',
          '',
        ]),
      ].join('\n');
    $('#studio-export').on('click', async (e) => {
      const item = e.target.closest('[data-export]');
      if (!item) return;
      keep();
      const kind = item.dataset.export;
      const name = slug(project.name);
      if (kind === 'page') save(`${page.id}.html`, new Blob([pageDocument(page)], { type: 'text/html' }));
      else if (kind === 'zip')
        save(
          `${name}.zip`,
          zip([
            ...project.pages.map((p) => ({ name: `${p.id}.html`, text: pageDocument(p) })),
            { name: 'project.json', text: JSON.stringify({ format: 'defuss-shadcn-studio/1', ...project }, null, 2) },
            { name: 'AGENTS.md', text: agentNotes() },
          ]),
        );
      else if (kind === 'json')
        save(
          `${name}.json`,
          new Blob([JSON.stringify({ format: 'defuss-shadcn-studio/1', ...project }, null, 2)], {
            type: 'application/json',
          }),
        );
      else if (kind === 'agent') {
        await navigator.clipboard.writeText(agentNotes()).then(
          () => status('Copied for an agent'),
          () => status('Copying was refused'),
        );
      } else if (kind === 'open') $('#studio-file').get(0).click();
      else if (kind === 'new') {
        openProject(fresh('Untitled app'));
        keep();
      }
    });
    // a project file comes in as a fork: a new id, so it never overwrites the project it was saved from
    $('#studio-file').on('change', async (e) => {
      const file = e.target.files?.[0];
      e.target.value = '';
      if (!file) return;
      try {
        const data = JSON.parse(await file.text());
        if (data?.format !== 'defuss-shadcn-studio/1' || !isProject(data)) throw new Error('not a Studio project');
        openProject({
          id: `p-${Date.now().toString(36)}`,
          name: data.name,
          pages: data.pages.map((p) => ({ id: slug(p.id), name: p.name, html: p.html })),
        });
        keep();
        status(`Opened ${data.name}`);
      } catch (err) {
        status(`Could not open: ${err.message}`);
      }
    });
  });
</script>
```

<h2 id="layout" class="h2-display">Layout</h2>

<DocText>The Studio is one <DocLink href="border-layout.html">Border Layout</DocLink>: the toolbar on top, the page in the center, and a resizable side on each hand that is itself a Border Layout. Each divider drags, moves with the arrow keys and folds on a double-click; the toolbar's panel buttons fold the sides too, and the sizes are kept in this browser.</DocText>

<DocText>Every view on the sides is a <DocLink href="panel.html">Panel</DocLink>, as in an application's layout. Minimize one and its region shrinks to the title bar, so its neighbour takes the room; the Studio remembers minimized panels in this browser. Maximize one and it covers its column until you restore it. The panel in the middle of a column - Components, Properties - only maximizes: its neighbour's minimize gives it the whole column. Everything is dense (<code>data-density="compact"</code>): the panels' title bars, the trees' rows, the cards.</DocText>

<DocText><strong>West, the library</strong> - a <DocLink href="tree-view.html">Tree View</DocLink> of the components of these docs: the sidebar sections that hold components, with their sidebar icons, their pages (sub-pages nested), and on each page first its component alone, in every kind the docs use it - h1 to h4 on Typography, every variant, size and state of Button the docs use - then its examples by name: "Japanese text" on Typography, "Multi-open" on Accordion. The components alone are the individual examples, kept in each component's parts file beside its sources (<code>button.parts.md</code>) - the docs pages show none of them - and verify keeps them complete: every component an example is made of has one of each kind it is used in. A picked entry shows below the tree in a frame of its own, with the page's stylesheets and no script: what a drop puts on the page, as the canvas will show it. One on the page of a wide composition (an organism, a block, a template) is laid out at a desktop width and scaled down. Drag it onto the page - from the preview, or straight from its row in the tree - or click it to put it into or after the selected element. The tree loads with the Studio; a page's entries load when one of them is picked, or when the pointer comes over one of its rows.</DocText>

<DocText><strong>East, the inspector</strong> - on top, a second Tree View holds the selection: the path from the page down to the selected element, which is highlighted, and every element inside it down to the deepest. Clicking a row selects its element; with nothing selected the tree is the whole page. It takes the height it needs, between a fifth and half of the inspector: a fixed region with the Border Layout's <code>data-fit</code>. Below it, the <DocLink href="property-grid.html">Property Grid</DocLink> shows the selected element's text, classes and attributes. The classes edit in a <DocLink href="combobox.html">Combobox</DocLink> tag input: the element's own classes first, then the classes its component owns (a Card's <code>card-header</code>, <code>card-title</code>...), then every utility class of the system by module - Layout, Sizing, Shapes, Accessibility; type to filter, or to add a class none of them lists. Under the properties sits the component's state, again as high as it needs (<code>data-fit</code>, up to half the column); with no state to show it folds to its title bar.</DocText>

<h2 id="state" class="h2-display">State</h2>

<DocText>A component with a script draws its markup from its state: its <code>render()</code> gives the markup of every state, and the next render would undo an edit of that markup. So in the Studio such a component is one locked unit (the Visual Editor's <code>lock()</code>): it moves, copies and goes as a whole, nothing drops into it, and its elements show read only in the Property Grid. It changes through its state - a <DocLink href="tree-grid.html">Tree Grid</DocLink> lists the states of its schema, with the controls of the <DocLink href="code-example.html">HTML Preview Editor</DocLink>'s State tab.</DocText>

<DocText>A change runs where the State tab runs it: a hidden HTML Preview Editor holds the component with its script, the value is set there the way the State tab sets it, and the markup that goes back into the page is what the component's <code>render()</code> gives for the state it landed in. The live markup would not do: it carries what the runtime adds - <code>data-init</code>, ARIA wiring - and a page loading it would not start the component again. A component without a script has no state: the State panel folds to its title bar (the Studio's own fold, not remembered - a panel you minimized stays as you left it), a card in it says so, and every element of the component is edited directly.</DocText>

<h2 id="the-rad-loop" class="h2-display">The RAD loop</h2>

<DocText>Rapid Agentic Development has two halves that speak one language: an agent writes markup from the component skills, a person shapes it here, and either one continues from the other's work. Nothing is translated on the way - the Studio's library is the docs' examples, written as the skills teach, its output is markup, and the verifier checks the result the same way it checks every page.</DocText>

```mermaid label="The RAD loop" caption="One language both ways: the skills' markup. The Studio adds the eyes, the agent the speed, verify the proof."
flowchart LR
    Skills["component skills<br/>(markup to copy)"] --> Agent["agent writes<br/>a page"]
    Agent -- "Open in Studio" --> Studio["person edits<br/>in the Studio"]
    Studio -- "Copy for an agent" --> Agent
    Studio --> Export["HTML pages<br/>app ZIP"]
    Agent --> Verify["verify<br/>tests, e2e"]
    Export --> Verify
```

<DocText><strong>From the docs into the Studio</strong> - an example's source travels in the address fragment (<code>full-studio.html#source=</code>, compressed) and opens as a new project. Nothing is sent to a server. The live examples on this site will carry an <em>Open in Studio</em> button for it once the Studio leaves alpha - until then the button is hidden.</DocText>

<DocText><strong>From the Studio to an agent</strong> - <em>Copy for an agent</em> (Export menu) writes Markdown: the project's pages as HTML and, for every component they use, the link to its skill at this release. Paste it into any harness with the <DocLink href="component-skills.html">component skills</DocLink> and ask for the next step - the agent changes markup it can read, in the language it was taught. The app ZIP carries the same notes as <code>AGENTS.md</code>.</DocText>

<DocText><strong>Kept in this browser</strong> - projects are stored locally as they are edited (one store, <code>studio:projects</code>); the project JSON moves them between browsers. An imported project is a copy with a new id, so it never overwrites the one it came from.</DocText>

<h2 id="what-is-exported" class="h2-display">What is exported</h2>

<DocText>A page is a complete HTML document: the page's markup, the system's core and all bundles from the CDN, pinned to this release, plus any extra bundle the page uses (Mermaid, math, the editors). The ZIP holds every page, <code>project.json</code> and <code>AGENTS.md</code> - serve the folder over HTTP and it runs as it previewed.</DocText>

<h2 id="limits" class="h2-display">Limits</h2>

<DocText>The canvas and the example frames show each component's markup without running it - a chart or a diagram stays empty there until Preview runs the page. An example's scripts are not part of what drops: the canvas's parser removes every <code>&lt;script&gt;</code>, data blocks included, so a component fed by one (a Property Grid's source, a diagram's spec, a grid's records) arrives empty. An example's <code>&lt;style&gt;</code> comes along and is kept with the page. The state of a component is read from its running instance; one that the markup alone cannot tell (an Accordion opened item by item reads as its default state) shows that. Projects stay in this browser unless exported.</DocText>

</DocPage>
