# Managing AdapTable State at Run-Time

Canonical page: https://www.adaptabletools.com/docs/dev-guide-adaptable-state-management

- The primary place to manage State at run-time is in AdapTable DevTools
- Additionally, the State Management Module inside AdapTable contains much of the same functionality

AdapTable State usually just 'happens' without the User being aware of the persistence mechanism or needing to do anything in particular.

But sometimes State doesn't behave the way you expect, or you might need to manage it in other ways.

Accordingly, AdapTable provides 2 resources to enable AdapTable State to be managed at run-time:
- AdapTable DevTools in Chrome - has a comprehensive State Management section
- State Management Module - available in the Settings Panel (hidden by default)

## AdapTable DevTools

[AdapTable DevTools](https://www.adaptabletools.com/docs/dev-guide-support-devtools/index.md) records **snapshots** of Adaptable State as the Grid runs — tag, restore, compare, upload/download JSON, and migrate — without entitling the in-app module.

Install and pick an instance on [AdapTable DevTools](https://www.adaptabletools.com/docs/dev-guide-support-devtools/index.md). Handbook walkthrough — [DevTools — Manage State](https://www.adaptabletools.com/docs/dev-guide-support-devtools-manage-state/index.md). Inspect versions and layout first — [DevTools — Grid Info](https://www.adaptabletools.com/docs/dev-guide-support-devtools-grid-info/index.md).

## State Management Module

The Statement Management Module also allows run-time users to import and export AdapTable State.

Its functionality can be accessed in 3 UI components:

- The `Manage State` section in the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md)
- The `Manage State` [Toolbar](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md) in the Dashboard
- The `Manage State` [Tool Panel](https://www.adaptabletools.com/docs/ui-tool-panel/index.md) in the AdapTable Tool Panel Component

- Due to its more "support-like" nature, the State Management Module is **`Hidden` by default**
- To make it available, set its [Entitlement](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) to `Full` (or `ReadOnly`) for those users who need it:

```ts
entitlementOptions: {
  moduleEntitlements: [{ adaptableModule: 'StateManagement', accessLevel: 'Full' }],
},
```

- Setting `defaultAccessLevel` to `Full` doesn't unhide the Module; it must be entitled explicitly in `moduleEntitlements`

### Module Functionality

All 3 Manage State components contain 4 State-related options:

- **Clearing User State**
- **Loading Initial Adaptable State** (from a JSON file)
- **Exporting the AdapTable State** - to Clipboard, Console or JSON
- **Exporting Initial Adaptable State** - to Clipboard, Console or JSON

Clearing User State will re-load the initial [Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md) that was provided

- If using [Local Storage](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md#local-storage), AdapTable will automatically clear what is in the User's State
- If using [Remote Storage](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md#remote-storage), AdapTable will invoke the `clearState` function that was provided at design-time

**Example: State Management Module**

Managing Adaptable State with State Management Module

- This demo opens the State Management page of the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'State Management Module',
  initialState: {
    Dashboard: {
      ModuleButtons: ['StateManagement'],
      Tabs: [
        {
          Name: 'State',
          Toolbars: ['StateManagement'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'description',
            'open_issues_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.settingsPanelApi.openSettingsPanel('StateManagement');
};
```

### Reloading Initial State

The Manage State panel allows you to re-apply your Initial Adaptable State using a JSON file.

This is done using the `Load Initial Adaptable State` button.

When clicked, AdapTable will replace the current State with the State in the uploaded file.

**Example: Load Initial Adaptable State**

Load Initial Adaptable State from a downloadable JSON file

- The demo illustrates how to reload the [Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md) using the `Manage State` Settings Panel
- Initial State includes a Format Column on `Name` (blue). **Change Format Columns** replaces it with runtime styles on `Github Stars` and `Language`; reloading from the downloadable file restores `Name`

- On load, confirm `Name` is styled blue (from Initial State)
- Click **Change Format Columns** — `Name` styling is removed and `Github Stars` (yellow) / `Language` (green) appear instead
- Download this file: <DownloadFile href="/data/initial-adaptable-state.json">initial-adaptable-state.json</DownloadFile>
- Open the Settings Panel using the **Manage State** module button, and then click **Load Initial Adaptable State** to select the downloaded file
- Runtime styles disappear and `Name` (blue) returns — confirming the Grid was restored from the file

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  initialState.ts
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableButton,
  AdaptableOptions,
  DashboardButtonContext,
  FormatColumn,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {initialState} from './initialState';

const INITIAL_FORMAT_COLUMN_NAME = 'formatColumn-name-initial';

const runtimeFormatColumns: FormatColumn[] = [
  {
    Name: 'formatColumn-github_stars-runtime',
    Scope: {
      ColumnIds: ['github_stars'],
    },
    Style: {
      BackColor: 'var(--ab-color-palette-21)',
      ForeColor: 'var(--ab-color-palette-13)',
      FontWeight: 'Bold',
    },
  },
  {
    Name: 'formatColumn-language-runtime',
    Scope: {
      ColumnIds: ['language'],
    },
    Style: {
      BackColor: 'var(--ab-color-palette-20)',
      ForeColor: 'var(--ab-color-palette-13)',
      FontWeight: 'Bold',
    },
  },
];

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Load Initial Adaptable State',
  adaptableStateKey: 'docs/LoadInitialStateDemo',
  initialState,
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Change Format Columns',
        buttonStyle: {
          tone: 'info',
          variant: 'raised',
        },
        onClick: (
          _button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const formatColumnApi = context.adaptableApi.formatColumnApi;

          const initialFormatColumn = formatColumnApi.getFormatColumnByName(
            INITIAL_FORMAT_COLUMN_NAME
          );
          if (initialFormatColumn) {
            formatColumnApi.deleteFormatColumn(initialFormatColumn);
          }

          const formatColumnsToAdd = runtimeFormatColumns.filter(
            formatColumn =>
              !formatColumnApi.getFormatColumnByName(formatColumn.Name)
          );

          if (!initialFormatColumn && formatColumnsToAdd.length === 0) {
            context.adaptableApi.systemStatusApi.setInfoSystemStatus(
              'Format Columns already changed — load Initial State to restore Name'
            );
            return;
          }

          if (formatColumnsToAdd.length > 0) {
            formatColumnApi.addFormatColumns(formatColumnsToAdd);
          }

          context.adaptableApi.systemStatusApi.setInfoSystemStatus(
            'Replaced Name Format Column with Github Stars + Language — load Initial State to restore'
          );

          // TODO(adaptable-patch): remove after patch (Format Column refresh + UpdateStrategy KeepUserDefined)
          context.adaptableApi.gridApi.refreshColumns(['github_stars', 'language']);
        },
      },
    ],
  },
};
```

**`src/initialState.ts`**

```ts
import {InitialState} from '@adaptabletools/adaptable';

/**
 * Initial Adaptable State for this demo.
 * Kept in sync with /public/data/initial-adaptable-state.json (downloadable for the Load button).
 */
export const initialState: InitialState = {
  Dashboard: {
    ModuleButtons: ['StateManagement'],
    Tabs: [
      {
        Name: 'State',
        Toolbars: ['SystemStatus'],
      },
    ],
  },
  Theme: {CurrentTheme: 'dark'},
  FormatColumn: {
    Revision: 1,
    FormatColumns: [
      {
        Name: 'formatColumn-name-initial',
        Scope: {
          ColumnIds: ['name'],
        },
        Style: {
          BackColor: '#1e88e5',
          ForeColor: 'var(--ab-color-palette-14)',
          FontWeight: 'Bold',
        },
      },
    ],
  },
  Layout: {
    CurrentLayout: 'Standard Layout',
    Layouts: [
      {
        Name: 'Standard Layout',
        TableColumns: [
          'name',
          'language',
          'github_stars',
          'license',
          'created_at',
          'has_wiki',
          'updated_at',
          'pushed_at',
          'github_watchers',
          'description',
          'open_issues_count',
        ],
        AutoSizeColumns: true,
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = (_info: AdaptableReadyInfo) => {
  // Initial State styles Name (blue); "Change Format Columns" swaps that for runtime styles
};
```
