# Layouts and chart state (/vela-pro/persistence/layouts)



A `VelaWorkspace` serializes its complete configuration into a single **state document** containing the grid layout and each chart's symbol, timeframe, settings, drawings, and indicators. You can read the current state with `getState()`, restore it with `applyState()`, enable automatic persistence via `persist`, or build custom workflows such as named layouts, workspace tabs, and shareable links.

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: '2h',
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
});

// Restore any document previously returned by getState().
const res = await fetch('/api/users/me/workspace');
if (res.ok) workspace.applyState(await res.json());

// Save the workspace as a single JSON-serializable document.
const save = (): void => {
    const body = JSON.stringify(workspace.getState());
    // keepalive lets the request finish after navigation. Browsers cap keepalive bodies at 64 KiB.
    const init = { method: 'PUT', headers: { 'content-type': 'application/json' }, body, keepalive: body.length < 60_000 };
    fetch('/api/users/me/workspace', init).catch(() => {});
};
workspace.on('state:changed', save);
window.addEventListener('pagehide', save);
```

`state:changed` fires approximately 500 ms after the most recent change so splitter drags or rapid edits coalesce into a single event. Because the event carries no payload, call `workspace.getState()` inside your listener. A workspace without `persist` enabled does not flush pending changes automatically when the page unloads, so register a `pagehide` listener when saving manually.

## State document structure [#state-document-structure]

The following example shows a trimmed state document for a two-chart workspace:

```json
{
    "version": 1,
    "layout": "2h",
    "activeCellId": "c1",
    "timezone": "Etc/UTC",
    "sync": { "crosshair": true },
    "favorites": ["trendline", "fibretracement"],
    "timeframeFavorites": ["15", "60", "D"],
    "drawingTools": { "magnet": "weak" },
    "panels": { "open": "vela-pro.watchlist", "widths": { "vela-pro.watchlist": 360 } },
    "charts": [
        {
            "id": "c1",
            "symbol": "binance:BTCUSDT",
            "provider": "binance",
            "timeframe": "60",
            "priceStyle": "candles",
            "rendererConfig": { "version": 1, "priceScale": { "mode": "price", "log": false }, "chartTypes": { "tpo": { "session": "week" } } },
            "drawings": { "version": 1, "drawings": [{ "id": "d1", "type": "trendline", "paneId": "price", "anchors": [{ "time": 1731326400000, "price": 81250 }, { "time": 1731585600000, "price": 90480 }] }] },
            "indicators": { "manifest": ["EMA 20"], "natives": ["volume", { "type": "rsi", "inputs": { "length": 21 } }] },
            "ext": { "velapro.indicators": [{ "name": "Desk levels", "script": "//@version=5\nindicator(\"Desk levels\", overlay = true)\n..." }] }
        },
        { "id": "c2", "symbol": "binance:ETHUSDT", "timeframe": "15", "priceStyle": "footprint" }
    ],
    "ext": {
        "velapro.bottomDock": { "open": true, "active": "vela-pro.strategy", "height": 320 },
        "velapro.orderbook": { "cumulative": true }
    }
}
```

| Field                                                                                         | Description                                                                                                                                                                                                                                     |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `version`                                                                                     | Schema version, always `1`. Documents with any other version are ignored.                                                                                                                                                                       |
| `layout`                                                                                      | Layout identifier, such as a built-in preset (`'1'`, `'2h'`, `'2v'`, `'4'`, `'8'`), a generated grid ID (`g3x2`), or a custom ID registered via `registerLayout`. Single-chart workspaces (`layout: false`) serialize `'1'`.                    |
| `charts`                                                                                      | Ordered array of chart cells. `id` matches the key in your `cells` constructor option, or defaults to `c1`, `c2`, and so on. Charts hidden when switching to a smaller layout remain in this array so expanding the layout later restores them. |
| `charts[i].symbol`, `timeframe`, `priceStyle`                                                 | Active market and chart style for the cell, including Vela Pro styles such as `footprint` and `tpo`.                                                                                                                                            |
| `charts[i].rendererConfig`                                                                    | Serialized chart settings dialog state, including colors, scales, grid lines, margins, and per-style settings under `chartTypes`.                                                                                                               |
| `charts[i].drawings`                                                                          | Output of `chart.drawings.toJSON()` for the chart's active symbol. See [Drawing persistence](/vela-pro/persistence/stores/drawings).                                                                                                            |
| `charts[i].indicators`                                                                        | Built-in indicators and manifest scripts active on the chart. See [Indicator persistence](/vela-pro/persistence/stores/indicators).                                                                                                             |
| `ext` and `charts[i].ext`                                                                     | Namespaced extension maps written by features, modules, and custom persistence handlers. See [Plugin state](/vela-pro/persistence/stores/plugin-state).                                                                                         |
| `favorites`, `timeframeFavorites`, `drawingTools`, `panels`, `sync`, `timezone`, `trackSizes` | Workspace-wide UI preferences shared across all charts in the layout.                                                                                                                                                                           |

## Automatic persistence [#automatic-persistence]

Setting `persist` on `VelaWorkspace` enables automatic load on startup and debounced writes whenever workspace state changes.

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import type { VelaStorage } from '@luxalgo/vela/widget';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

const url = (key: string): string => `/api/users/me/state/${encodeURIComponent(key)}`;

const storage: VelaStorage = {
    async get(key) {
        try {
            const res = await fetch(url(key));
            return res.ok ? await res.text() : null;
        } catch {
            return null;
        }
    },
    async set(key, value) {
        try {
            // keepalive lets the final write finish on unload. Browsers cap keepalive bodies at 64 KiB.
            await fetch(url(key), { method: 'PUT', body: value, keepalive: value.length < 60_000 });
        } catch {
            // Offline; the next state change writes the full document again.
        }
    },
};

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: 'main',
    storage,
});
```

| Option    | Default        | Description                                                                                                                                                                     |
| --------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `persist` | Disabled       | Pass `true` to store state under the key `vela-workspace`, or pass a custom string key to isolate multiple workspaces on the same page.                                         |
| `storage` | `localStorage` | Adapter implementing `get(key)` and `set(key, value)` (either synchronous or returning a `Promise`), plus an optional `remove(key)` method. Values are serialized JSON strings. |

Adapter lifecycle behavior:

* `get` runs once when the workspace is constructed. A synchronous return value is applied before the first paint. If `get` returns a `Promise`, the workspace renders your initial constructor options first and applies the saved document when the promise resolves. See [Server-side storage](/vela-pro/persistence/backend#workspace-state-and-editor-draft) to preload the document before construction and avoid a layout switch after first paint.
* `set` runs approximately 500 ms after the last state change and flushes immediately on `beforeunload` or `workspace.destroy()`. Every write receives the complete serialized document.
* Writes are not awaited by the workspace. Storage latency never blocks UI interactions, and rejected promises from `set` are not caught internally, so handle network errors inside `set`.
* `remove` is never called by `VelaWorkspace` and exists on `VelaStorage` for application-level reset helpers.

Vela's open-source core provides two built-in storage adapters: `localStorageAdapter(storageKey?)` from `@luxalgo/vela/widget` (used by default) and `memoryStorageAdapter()` from `@luxalgo/vela/workspace` (kept in memory for the lifetime of the page).

## Named layouts and tabs [#named-layouts-and-tabs]

Because each state document is self-contained, features like "Save layout as", saved layout menus, multi-tab workspaces, and shareable chart URLs require only a backend table and `getState()` / `applyState()`. `VelaWorkspace` does not store a list of named layouts internally.

```ts
import type { VelaWorkspace } from '@luxalgo/vela/workspace';

declare const workspace: VelaWorkspace;

interface LayoutEntry {
    id: string;
    name: string;
}

export async function listLayouts(): Promise<LayoutEntry[]> {
    const res = await fetch('/api/users/me/layouts');
    return res.ok ? ((await res.json()) as LayoutEntry[]) : [];
}

export async function saveLayoutAs(name: string): Promise<LayoutEntry> {
    const res = await fetch('/api/users/me/layouts', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ name, state: workspace.getState() }),
    });
    return (await res.json()) as LayoutEntry;
}

export async function loadLayout(id: string): Promise<void> {
    const res = await fetch(`/api/users/me/layouts/${encodeURIComponent(id)}`);
    if (res.ok) workspace.applyState(await res.json());
}
```

You can combine `persist` with named layouts so `persist` autosaves the user's active session while named layouts store explicit snapshots. Shareable links follow the same pattern because URL state encoding is not built into the workspace; store or encode `workspace.getState()` under your URL scheme and pass the decoded payload to `workspace.applyState()` on page load.

<Warning>
  When per-symbol drawing storage is enabled (the default in `enableVelaPro()`), switching between multiple named layouts or tabs inside the same workspace container requires configuring a dynamic `chartKey`. Otherwise, drawings brought in by one layout overwrite drawings saved for the same symbol in another layout. See [Drawing persistence](/vela-pro/persistence/stores/drawings#naming-charts-with-chartkey).
</Warning>

## In-place updates vs. full rebuilds [#in-place-updates-vs-full-rebuilds]

Calling `workspace.applyState()` executes one of two update paths depending on how the incoming document compares to the active workspace:

* **In-place update**: Selected when the incoming document has the same `layout` ID and identical chart `id` values in the exact same slot order. Every chart instance stays mounted while its symbol, timeframe, renderer settings, drawings, and indicators update to match the document. Existing chart references, event subscriptions, and built-in indicator handles remain valid. Script indicators are removed and re-added, invalidating any previously stored script handles.
* **Full rebuild**: Selected whenever the `layout` ID, chart count, or chart IDs differ. Every existing chart is destroyed and recreated from the document. The workspace emits `cell:destroyed` and `cell:created` for each cell, followed by `layout:changed`.

Store cell IDs rather than holding direct references to chart instances, resolve `workspace.cell(id)?.chart` when needed, and subscribe to `cell:created` to wire per-chart listeners across rebuilds. A single-chart workspace constructed with `layout: false` remains single-chart regardless of the document's `layout` field and restores `charts[0]`.

## Schema validation [#schema-validation]

`applyState()` accepts `unknown` so documents loaded from a server, URL, or file import are validated safely before mutating workspace state:

* Values that are not plain objects, omit a string `layout`, or specify a `version` other than `1` are ignored without throwing an error or modifying the workspace.
* Malformed individual fields are dropped while valid fields still apply. Chart entries without a string `id` are skipped, and if duplicate chart IDs appear, the last matching entry takes precedence.
* Each chart validates `rendererConfig` and `drawings` field by field and drawing by drawing.
* Extension payloads in `ext` and `charts[i].ext` pass through unmodified, preserving keys written by features or modules that are disabled in the current session. Each extension handler validates its payload when restoring.
* An unregistered `layout` ID leaves the current layout active. Call `registerLayout` before applying a state document that references a custom layout.

To validate an untrusted document outside a workspace instance (for example, before saving an imported file), call `sanitizeState(doc)` from `@luxalgo/vela/workspace`. It returns the sanitized document or `null` if the input cannot be used.

## Related [#related]

* [Configuration precedence](/vela-pro/persistence/precedence)
* [Server-side storage](/vela-pro/persistence/backend)
* [State and persistence in the core workspace guide](/vela/user/workspace#state--persistence)
