Plugin state
Persist custom panel, widget action, and module state inside the workspace state document using registerStatePersistence.
Custom side panels, widget actions, and domain modules can store layout-level state directly inside the workspace state document by calling registerStatePersistence from @luxalgo/vela/plugin (part of Vela's open-source core). Registered state is saved automatically when persist is enabled, included in workspace.getState(), restored by workspace.applyState(), and carried along with named or shared layouts without requiring a dedicated storage endpoint.
Each persistence handler owns one namespaced key inside one of the state document's two ext maps. Using scope: 'global' stores a single entry at the document root (ext[key]), while scope: 'cell' stores an entry per chart cell (charts[i].ext[key]) that stays bound to that specific chart.
Document-scoped state
Use scope: 'global' for workspace-wide preferences, such as side panel settings or filter states:
import { registerSidePanel, registerStatePersistence } from '@luxalgo/vela/plugin';
interface NewsPrefs {
compact: boolean;
sources: string[];
}
let prefs: NewsPrefs = { compact: false, sources: ['wire'] };
registerStatePersistence({
key: 'acme.news', // flat vendor-namespaced key: 'vendor.feature'
scope: 'global',
serialize: () => prefs,
restore(payload) {
// Treat persisted payloads as untrusted and validate every field.
if (!payload || typeof payload !== 'object') return;
const saved = payload as Partial<Record<keyof NewsPrefs, unknown>>;
prefs = {
compact: typeof saved.compact === 'boolean' ? saved.compact : prefs.compact,
sources: Array.isArray(saved.sources) ? saved.sources.filter((s): s is string => typeof s === 'string') : prefs.sources,
};
},
});
registerSidePanel({
id: 'acme.news',
title: 'News',
icon: 'list',
mount: (ctx, body) => {
const toggle = document.createElement('button');
toggle.textContent = 'Compact rows';
toggle.addEventListener('click', () => {
prefs = { ...prefs, compact: !prefs.compact };
ctx.stateChanged(); // notify the workspace to schedule a save
});
body.append(toggle);
return {};
},
});Call ctx.stateChanged() whenever external state mutates. While the workspace automatically observes built-in mutations (such as symbol switches, drawings, and indicator edits), it cannot detect changes to external variables unless notified. Calling ctx.stateChanged() coalesces with built-in changes into a single debounced state:changed event and storage write.
Vela Pro's built-in modules use this exact mechanism for layout preferences, storing order book column settings under velapro.orderbook and calendar filters under velapro.calendar with scope: 'global'.
Chart-scoped state
Scripts added programmatically via ctx.addIndicator() participate in the chart's undo history for the active session, but the workspace does not serialize them automatically. Registering a scope: 'cell' handler persists those indicators per chart cell and restores them under deterministic IDs:
import { inputDeltas, registerStatePersistence, registerWidgetAction, type InputValue } from '@luxalgo/vela/plugin';
const PREFIX = 'acme:';
const SCRIPTS: Record<string, { name: string; script: string }> = {
trend: { name: 'Acme Trend', script: '//@version=5\nindicator("Acme Trend", overlay = true)\nplot(ta.ema(close, 50))' },
};
registerStatePersistence({
key: 'acme.scripts',
scope: 'cell',
serialize(ctx) {
const mine = ctx.chart.indicators().filter((h) => h.id.startsWith(PREFIX));
if (mine.length === 0) return undefined; // omit key when no matching scripts exist on this chart
return mine.map((h) => ({ slug: h.id.slice(PREFIX.length), inputs: inputDeltas(h.inputs, h.inputValues()), hidden: !h.visible }));
},
restore(payload, ctx) {
if (!Array.isArray(payload)) return;
for (const item of payload as unknown[]) {
if (!item || typeof item !== 'object') continue;
const { slug, inputs, hidden } = item as { slug?: unknown; inputs?: unknown; hidden?: unknown };
const known = typeof slug === 'string' ? SCRIPTS[slug] : undefined;
if (!known) continue;
const values = inputs && typeof inputs === 'object' ? (inputs as Record<string, InputValue>) : undefined;
ctx.addIndicator({ ...known, id: `${PREFIX}${slug}`, language: 'pine', inputs: values, hidden: hidden === true });
}
},
});
registerWidgetAction({
id: 'acme.add-trend',
target: 'topbar',
label: 'Acme Trend',
run: (ctx) => ctx.addIndicator({ ...SCRIPTS.trend!, id: `${PREFIX}trend`, language: 'pine' }),
});Note three design details in the cell handler above:
- Store script identifiers instead of source code for application-owned scripts so state documents stay compact and bug fixes in
SCRIPTSpropagate to saved layouts automatically. Store raw source code only when persisting user-authored scripts. - Persist input deltas using
inputDeltasfrom the core so untouched inputs continue to inherit updated script defaults in future releases. - Restore via the handler's
ctx.addIndicator()rather than an outer workspace reference. Thectxpassed torestoretargets the specific chart cell being restored (even when it is not the active cell) and mounts the indicator without adding a step to the undo/redo stack.
Registration rules
registerStatePersistence enforces five lifecycle rules:
- Register before constructing workspaces.
VelaWorkspacereads the state persistence registry at construction time, following the same initialization order asenableVelaPro(). Registering an existingkeya second time replaces the previous handler. - Keep
serializesynchronous and lightweight.serializeexecutes on everygetState()call and every debouncedpersistwrite. Return a JSON-serializable value, orundefinedto omit your key fromext. Callctx.stateChanged()whenever your state changes outside built-in chart events. restoreruns only when your key exists in the document. During initial persistence load andapplyState(),restoreexecutes after charts, scripting engines, and built-in/manifest indicators have mounted. Applying a document that omits your key skipsrestorerather than resetting your state.- Validate all
restorepayloads. The workspace treatsextentries as opaque JSON without schema validation and preserves unrecognizedextkeys across sessions where the owning handler is not registered. Always type-check fields insiderestore. - Select the matching
scope. Usecellscope for state bound to an individual chart's content andglobalscope for workspace-wide preferences.
Exceptions thrown inside serialize or restore are caught and logged by the workspace so failures in one handler cannot break other extensions. For the complete SDK specification, see State persistence in the core plugin SDK.
Choosing between ext and a separate store
Persisting state inside the workspace state document fits layout-coupled configuration, whereas a standalone storage adapter or port is preferable when:
- Data outlives individual layouts. User records such as watchlists, journal entries, and alert rules should remain consistent when switching between saved layouts and should not be bundled when sharing a layout link.
- Payloads are large or mutate rapidly. Every state change serializes and writes the entire workspace state document as a single payload.
- State is consumed outside a workspace. Standalone widgets mounted on non-chart pages and server-side background jobs have no workspace state document.
For layout-independent data, follow the same adapter pattern used by Vela Pro's built-in features: define a focused load / save interface with a localStorage fallback and accept a custom adapter during initialization. Standalone widgets mounted outside a workspace emit setting changes through props callbacks so your host page can store them directly; see Standalone widgets.