Studio state allows reports to be saved and restored. Reports can be created in edit mode, saved down as state, and then reloaded in view mode.
Saving and Restoring State Copy Link
import type {
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioApiReadyEvent,
AgStudioMode,
AgStudioPreDestroyedEvent,
AgStudioStateUpdatedEvent,
} from "ag-studio";
import { enableStudioDevValidations } from "ag-studio";
import { AgStudio } from "ag-studio-vue3";
import { createApp, defineComponent, ref, shallowRef } from "vue";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const HARDCODED_STATE: AgReportState = {
pages: [
{
id: "page-1",
widgets: {
"1": {
type: "grid",
dataMapping: {
cols: [
{ id: "medals.country" },
{ id: "medals.sport" },
{ id: "medals.gold", aggregation: "sum" },
{ id: "medals.silver", aggregation: "sum" },
{ id: "medals.bronze", aggregation: "sum" },
{ id: "medals.total", aggregation: "sum" },
],
},
},
"2": {
type: "column-chart-grouped",
dataMapping: {
categoryKey: [{ id: "medals.country" }],
valueKey: [
{ id: "medals.gold", aggregation: "sum" },
{ id: "medals.silver", aggregation: "sum" },
{ id: "medals.bronze", aggregation: "sum" },
],
},
},
},
widgetLayout: {
"1": {
xTrack: 0,
yTrack: 0,
xSpan: 24,
ySpan: 16,
},
"2": {
xTrack: 0,
yTrack: 16,
xSpan: 24,
ySpan: 16,
},
},
},
],
selectedPageId: "page-1",
panels: {
filters: {
collapsed: true,
},
},
};
const EMPTY_STATE: AgReportState = {
pages: [
{
id: "page-1",
},
],
selectedPageId: "page-1",
};
const VueExample = defineComponent({
template: `
<div style="height: 100%">
<div style="display: flex; flex-direction: column; height: 100%">
<div class="example-controls">
<div class="controls-row">
<button v-on:click="clearState()">Clear State</button>
<button v-on:click="saveState()">Save State</button>
<button v-on:click="restoreState()">Restore State</button>
<button v-on:click="hardcodedState()">Load Hardcoded State</button>
<button v-on:click="recreate()">Recreate Studio with Current State and History</button>
<button v-on:click="doUndo()">Undo</button>
<button v-on:click="doRedo()">Redo</button>
</div>
</div>
<ag-studio
v-if="studioVisible"
style="width: 100%; height: 100%;"
class="my-studio-container"
@api-ready="onApiReady"
:initialState="initialState"
:mode="mode"
:data="data"
@state-updated="onStateUpdated"
@studio-pre-destroyed="onStudioPreDestroyed"></ag-studio>
</div>
</div>
`,
components: {
"ag-studio": AgStudio,
},
setup(props) {
const studioApi = shallowRef<AgStudioApi | null>(null);
const initialState = ref<AgReportState>(HARDCODED_STATE);
const mode = ref<AgStudioMode>("edit");
const data = ref<AgDataSourcesDefinition | AgDataEngine>(null);
const savedState = ref<AgReportState>(EMPTY_STATE);
const studioVisible = ref(true);
const onStateUpdated: (event: AgStudioStateUpdatedEvent) => void = (
event: AgStudioStateUpdatedEvent,
) => {
console.log("State updated", event.state);
};
const onStudioPreDestroyed: (event: AgStudioPreDestroyedEvent) => void = (
event: AgStudioPreDestroyedEvent,
) => {
console.log("Studio state on destroy", event.state);
};
const clearState = () => {
studioApi.value.setState(EMPTY_STATE);
};
const saveState = () => {
const state = studioApi.value.getState();
console.log("Current state", state);
savedState.value = state;
};
const restoreState = () => {
studioApi.value.setState(savedState.value);
};
const hardcodedState = () => {
studioApi.value.setState(HARDCODED_STATE);
};
const doUndo = () => {
studioApi.value.undo();
};
const doRedo = () => {
studioApi.value.redo();
};
// `getHistory()` rather than `getState()`: it carries the live document as its `current`, so
// the rebuilt Studio comes back with the undo stack as well as the dashboard.
const recreate = () => {
const history = studioApi.value.getHistory();
studioVisible.value = false;
setTimeout(() => {
initialState.value = history;
data.value = undefined;
studioVisible.value = true;
});
};
const onApiReady = (params: AgStudioApiReadyEvent) => {
studioApi.value = params.api;
const getData = (data: any[]) => ({
sources: [{ id: "medals", data }],
});
fetch("https://www.ag-grid.com/studio/example-assets/olympic-winners.json")
.then((resp) => resp.json())
.then((respData) => (data.value = getData(respData)));
};
return {
studioApi,
initialState,
mode,
data,
studioVisible,
onApiReady,
onStateUpdated,
onStudioPreDestroyed,
clearState,
saveState,
restoreState,
hardcodedState,
recreate,
doUndo,
doRedo,
};
},
});
const app = createApp(VueExample);
app.mount("#app");
<ag-studio
:initialState="initialState"
/* other studio properties ... */>
</ag-studio>
this.initialState = {
pages: [
{
id: 'page-1',
widgets: {
'1': {
type: 'grid',
dataMapping: {
cols: [
{ id: 'medals.country' },
],
},
},
},
widgetLayout: {
'1': {
xTrack: 0,
yTrack: 0,
xSpan: 24,
ySpan: 16,
},
},
},
],
selectedPageId: 'page-1',
};State is provided to Studio on initialisation via the initialState property. It takes what getState() returned, or what getHistory() returned to bring the undo and redo stacks back with the report state - the example's "Recreate Studio with Current State and History" button does the latter, so the rebuilt Studio can still undo the changes made before it. Its Undo and Redo buttons call undo() and redo(), so the restored stacks can be stepped through.
Changes to state can also be stepped back and forward - see Undo & Redo.
State can be saved and restored on demand via the API methods getState() and setState().
Any time state changes, a stateUpdated event is emitted with the latest state. When Studio is destroyed, the studioPreDestroyed event is fired, which contains the latest state at the time.
These are all demonstrated in the above example. See the State API below for more details.
State is immutable. Studio uses reference equality to detect which parts of the state have changed, and updates them accordingly. If updating state and providing it back to Studio, ensure that a shallow copy is made to the depth of the changes.
Knowing What Changed Copy Link
stateUpdated carries a description of the change alongside the state, so a host can tell what to act on without comparing state itself.
State comes in two parts. Report state is the report itself - its widgets, layout, filters and schema - and durable reports true when a change moved it. View state is how that report is being looked at, such as the selected page or the panel sizes, and a change to it reports false.
durable says when to save rather than what to save: event.state is the whole snapshot either way, view state included. Test it to skip the saves that only a view change triggered, or save on every update to keep a reader's selected page and panel sizes up to date:
onStateUpdated: (event) => {
if (event.durable) {
save(event.state);
}
},changedKeys lists the top-level state properties now holding a different value, so a host syncing one part of the report state can skip an update that did not touch it:
onStateUpdated: (event) => {
if (event.changedKeys.includes('schema')) {
resyncColumns(event.state.schema);
}
},change describes the undo entry the update recorded, where it recorded one: its entryId, the labelKey naming it, the source saying who made it, and at, when it was written. It is absent where no entry was recorded - an undo or redo, a repair, the initial load, or a view-state change:
onStateUpdated: ({ change }) => {
if (change?.source.type === 'ai') {
showToast(`${change.source.agent} changed the dashboard`);
}
},See Undo & Redo for what a source can be, and for reading the same description off the history.
Order Studio's changes against a log of your own by change.at rather than by when the handler ran. Updates are debounced, so a change is written before the event carrying it arrives, and one coalesced over a drag reports when its last write landed:
onStateUpdated: ({ change }) => {
if (change) {
activity.push({ at: change.at, by: change.source, what: change.labelKey });
}
},Updates are coalesced: several changes landing together arrive as one event. changedKeys covers all of them, while change describes the last entry recorded among them.
Modes and State Copy Link
Switching between edit and view mode changes only what is shown and what is editable. The active state carries across the switch unchanged; Studio neither saves nor restores state on a mode change.
State changes made in view mode are emitted through stateUpdated exactly as in edit mode.
Applications that don't want to persist any view mode changes can do so themselves (e.g. where any edits made in view mode are discarded on returning to edit mode). Call getState() immediately before setting mode to 'view', and setState() with the saved state when setting mode back to 'edit':
const savedState = api.getState();
api.setProperty('mode', 'view');
// later, when returning to edit mode
api.setProperty('mode', 'edit');
api.setState(savedState); Changing Pages Copy Link
import {
createApp,
defineComponent,
onBeforeMount,
ref,
shallowRef,
} from "vue";
import { AgStudio } from "ag-studio-vue3";
import {
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioApiReadyEvent,
AgStudioMode,
AgStudioProperties,
enableStudioDevValidations,
} from "ag-studio";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const VueExample = defineComponent({
template: `
<div style="height: 100%">
<div style="display: flex; flex-direction: column; height: 100%">
<div class="example-controls">
<div class="controls-row">
<button v-on:click="updatePage('page-1')">Page 1</button>
<button v-on:click="updatePage('page-2')">Page 2</button>
</div>
</div>
<ag-studio
style="width: 100%; height: 100%;"
class="my-studio-container"
@api-ready="onApiReady"
:initialState="initialState"
:mode="mode"
:data="data"></ag-studio>
</div>
</div>
`,
components: {
"ag-studio": AgStudio,
},
setup(props) {
const studioApi = shallowRef<AgStudioApi | null>(null);
const initialState = ref<AgReportState | AgReportHistory>({
pages: [
{
id: "page-1",
widgets: {
"1": {
type: "grid",
dataMapping: {
cols: [
{ id: "medals.country" },
{ id: "medals.sport" },
{ id: "medals.gold", aggregation: "sum" },
{ id: "medals.silver", aggregation: "sum" },
{ id: "medals.bronze", aggregation: "sum" },
{ id: "medals.total", aggregation: "sum" },
],
},
},
},
widgetLayout: {
"1": {
xTrack: 0,
yTrack: 0,
xSpan: 24,
ySpan: 24,
},
},
},
{
id: "page-2",
widgets: {
"1": {
type: "column-chart-grouped",
dataMapping: {
categoryKey: [{ id: "medals.country" }],
valueKey: [
{ id: "medals.gold", aggregation: "sum" },
{ id: "medals.silver", aggregation: "sum" },
{ id: "medals.bronze", aggregation: "sum" },
],
},
},
},
widgetLayout: {
"1": {
xTrack: 0,
yTrack: 0,
xSpan: 24,
ySpan: 24,
},
},
},
],
selectedPageId: "page-1",
panels: {
filters: {
collapsed: true,
},
},
});
const mode = ref<AgStudioMode>("edit");
const data = ref<AgDataSourcesDefinition | AgDataEngine>(null);
function updatePage(pageId: string) {
const state = studioApi.value.getState();
studioApi.value.setState({
...state,
selectedPageId: pageId,
});
}
const onApiReady = (params: AgStudioApiReadyEvent) => {
studioApi.value = params.api;
const toStudioData = (data) => ({
sources: [{ id: "medals", data }],
});
fetch("https://www.ag-grid.com/studio/example-assets/olympic-winners.json")
.then((resp) => resp.json())
.then((respData) => (data.value = toStudioData(respData)));
};
return {
studioApi,
initialState,
mode,
data,
onApiReady,
updatePage,
};
},
});
const app = createApp(VueExample);
app.mount("#app");
Reports support multiple pages. These are all defined in state, with the currently displayed page set via the top-level selectedPageId state property. The page can be changed by getting the latest state from Studio and setting back a copy with the selectedPageId updated.
const state = api.getState();
api.setState({
...state,
selectedPageId: 'page-2',
}); Invalid State Copy Link
When state is invalid, Studio will do a "best-effort" attempt to load the state. This generally means removing invalid properties, which can leave widgets incomplete.
In Edit Mode, the UI can be used to fix the properties that were invalid, however in View Mode the user cannot make updates.
Studio will emit an errorRaised event with errorType: 'state' when there is invalid state (see Studio Events for how to listen to events). When in View Mode, where the report cannot be loaded properly, the event will have fatal: true.
It is recommended that you handle fatal error events by preventing the user from interacting with Studio. E.g. hiding Studio with your own error component, prompting the user to load a different report, switching into Edit Mode if the user has permissions, etc.
To help avoid invalid state, we strongly recommend creating state in the UI and then retrieving it from Studio. You can then make minor tweaks if required, rather than hand-crafting the entire state object.
State Versioning Copy Link
If there are breaking changes to the shape of the state object, Studio will try to automatically upgrade any provided state based on the version property.
version is always set with the current version when retrieving state from Studio.
If version is not set, Studio will assume that the state is for the current version, and will not perform any migrations.
Ensure that any saved-down state is read from Studio or has the version set. Otherwise you will have to manually update it if there are breaking changes to the shape of the state object.
State API Copy Link
Properties Copy Link
Initial state for Studio. Only read once on initialization. Can be used in conjunction with api.getState() to save and restore Studio state.
Pass what api.getHistory() returned, rather than what api.getState() did, to restore the
undo and redo history alongside the report state it was recorded against - the history carries
that state as its current. See AgHistoryOptions for what a restored history
keeps. |
API Methods Copy Link
Get the current state of Studio.
Can be used in conjunction with the initialState Studio property
or api.setState() to save and restore Studio state.
The object returned is Studio's own state rather than a copy. Treat it as read-only and
build a new object to pass to api.setState(): mutating this one and handing it back
updates nothing on screen. |
Set the current state of Studio.
Can be used in conjunction with api.getState() or onStateUpdated
to save and restore Studio state.
The state is expected to be a full state object, not a partial state object.
State must be updated immutably as Studio uses reference equality
to determine which parts of state have changed.
options names the change in the undo history and says who made it; see
AgSetStateOptions. |
Events Copy Link
State has been updated. |
Invoked immediately before Studio is destroyed. This is useful for cleanup logic that needs to run before Studio is torn down. |