# Configuring Layouts

Canonical page: https://www.adaptabletools.com/docs/handbook-layouts-configuring

- **`layoutOptions`** on [Adaptable Options](https://www.adaptabletools.com/docs/technical-reference-adaptable-options/index.md) configure Layout behaviour that is not stored in Layout State
- Includes auto-creation, default properties on new layouts, row-selection checkboxes, pivot cell previews, extensions UI, and Settings Panel layout list preview
- Advanced **manual Layout persistence** uses [State Options](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md) together with Layout API — see [Suppressing Auto-Save](#suppressing-auto-save) below

[Layouts](https://www.adaptabletools.com/docs/handbook-layouts/index.md) · [Topics in this Section](https://www.adaptabletools.com/docs/handbook-layouts/index.md#topics-in-this-section).
Layout State and API — [Layout Technical Reference](https://www.adaptabletools.com/docs/technical-reference-layouts/index.md).

## Topics on this Page

| Topic | Summary |
| ----- | ------- |
| [Layout Options catalogue](#layout-options-catalogue) | Where each `layoutOptions` property is documented |
| [Layout View Options](#layout-view-options) | Settings Panel inline layout preview |
| [Deleted special columns](#deleted-special-columns) | Remove Calculated / FreeText columns from all Layouts |
| [Suppressing Auto-Save](#suppressing-auto-save) | Optional manual Layout persistence |
| [Discarding unsaved changes](#discarding-unsaved-changes) | Roll back a Layout when the user switches away |

## Layout Options Catalogue

Most `layoutOptions` properties have dedicated handbook pages so this section does not repeat their full behaviour.

| Property | Purpose | Handbook |
| -------- | ------- | -------- |
| `autoCreateLayout` | First-run Layout from ColDefs | [Default Layouts](https://www.adaptabletools.com/docs/handbook-layouts-default/index.md) |
| `layoutCreationDefaultProperties` | Defaults when users create a Layout | [Default Layouts](https://www.adaptabletools.com/docs/handbook-layouts-default/index.md) |
| `enableLayoutExtensionsUI` | UI to add/remove extended objects | [Extending Layouts](https://www.adaptabletools.com/docs/handbook-layouts-extending/index.md) |
| `isRowSelectionCheckboxVisible` | Per-row selection checkbox visibility | [Table Layouts — Row Selection](https://www.adaptabletools.com/docs/handbook-layouts-table-row-selection/index.md#checkbox-visibility) |
| `pivotPreviewColumns` | Extra columns in pivot cell expand table | [Pivot Layouts](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md#opening-pivot-cells-as-tables) |
| `layoutViewOptions.maxColumnsToDisplay` | Column names shown in Settings Panel layout preview | [Layout View Options](#layout-view-options) (this page) |
| `autoRemoveDeletedColumnsFromLayouts` | Drop deleted special columns from Layouts | [Deleted special columns](#deleted-special-columns) (this page) |

Do not set `layoutTagOptions` — extend objects with `LayoutExtensions` on Layout State. See [Extending Layouts](https://www.adaptabletools.com/docs/handbook-layouts-extending/index.md).

## Layout View Options

`layoutViewOptions` controls how Layouts appear in the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md) list (not column behaviour inside the grid).

### `layoutViewOptions.maxColumnsToDisplay`

How many column names to show in the inline Layout preview in Settings Panel

Truncates the column summary in each Layout row when many columns are visible. Does not limit columns in the grid itself.

```ts {3-5}
layoutOptions: {
  layoutViewOptions: {
    maxColumnsToDisplay: 15,
  },
},
```

## Deleted Special Columns

When a [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) or [FreeText Column](https://www.adaptabletools.com/docs/handbook-freetext-column/index.md) is deleted, AdapTable can remove that column from every Layout (column lists, sorts, grouping, and other Layout properties).

### `autoRemoveDeletedColumnsFromLayouts`

Remove deleted Calculated and FreeText columns from all Layouts

Set to `false` only if you manage Layout cleanup yourself after column deletion.

```ts {3}
layoutOptions: {
  autoRemoveDeletedColumnsFromLayouts: true,
},
```

## Suppressing Auto-Save

Layouts, like all AdapTable objects, **save automatically** as soon as they are changed.

Whenever a Column is grouped, resized, pinned etc, the change is immediately persisted to AdapTable State.

Sometimes this is not desired behaviour, and developers prefer to manually control when a Layout is saved.

In other words, run-time users can only make temporary changes to Layouts, and the actual state persistence is imperatively driven.

The `persistState` function in [State Options](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md) is used to write a **snapshot** of last-saved Layouts instead of the running Layout State.

Other AdapTable objects (e.g. Format Columns) continue to persist automatically.

Developers can then persist Layouts on demand:

- **Persist ALL Layout Changes** — save every Layout in the running State
- **Persist CURRENT Layout Changes** — merge only the Current Layout into the snapshot

### Discarding Unsaved Changes

A common requirement is that unsaved edits are **lost when the user leaves a Layout**.

For example:

1. `First Layout` has columns `A`, `B`, `C`
2. The user reorders them to `C`, `B`, `A`
3. The user clones it as `Second Layout` (which keeps `C`, `B`, `A`)
4. Switching back to `First Layout` shows `A`, `B`, `C` again

This is implemented by listening to the [Layout Changed Event](https://www.adaptabletools.com/docs/handbook-layouts-monitoring/index.md) and, on a `LAYOUT_SELECT`, restoring the abandoned Layout from the last persisted snapshot via `createOrUpdateLayout` in [Layout API](https://www.adaptabletools.com/docs/technical-reference-layouts/index.md).

If the abandoned Layout is not in the snapshot (e.g. a freshly cloned Layout), it is left as-is.

This demo is a cut down version from examples in the [Guide to Controlling AdapTable State Persistence](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md#controlling-state-persistence).
See the demos there for full explanations of this advanced topic.

This pattern only works with a custom `persistState` hook.
In a default setup there is no "last saved" Layout to roll back to.

**Example: Manually Saving Layouts**

Non-auto saving of Layouts

- In this demo we prevent the auto-saving of Layouts
- Changes to Layouts stay local until they are explicitly persisted; we keep a snapshot of last-saved Layouts and provide 4 Dashboard Buttons:
  - `Persist ALL Layout Changes` — **manually** saves every Layout to AdapTable State
  - `Persist CURRENT Layout Changes` — **manually** saves only the Current Layout
  - `Undo Layout Changes` — replaces any locally saved changes to Layouts with the **last saved** version in AdapTable State
  - `Reset Layout Changes` — replaces any locally saved changes to Layouts with the **initial** version in AdapTable State
- Switching away from a Layout **discards its unsaved changes** (the Layout is restored from the last persisted snapshot). A freshly cloned Layout is left as-is because it is not yet in that snapshot
- Note: only Layouts are not auto-saved — changes to other objects (e.g. changing the back colour of the Format Column on the `Github Stars` Column) are automatically persisted

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]
  stateOptions.ts
  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';
import {
  customStateOptions,
  persistAllLayoutChanges,
  persistCurrentLayoutChanges,
  resetLayoutChanges,
  undoLayoutChanges,
} from './stateOptions';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Layout Save',
  stateOptions: customStateOptions,
  dashboardOptions: {
    customToolbars: [
      {
        name: 'PersistLayoutChanges',
        toolbarButtons: [
          {
            label: `Persist ALL Layout Changes`,
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              persistAllLayoutChanges(adaptableApi);
            },
            buttonStyle: {
              variant: 'raised',
              tone: 'success',
            },
          },
          {
            label: `Persist CURRENT Layout Changes`,
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              persistCurrentLayoutChanges(adaptableApi);
            },
            buttonStyle: {
              variant: 'raised',
              tone: 'info',
            },
          },
        ],
        title: 'Save Changes',
      },
      {
        name: 'UndoLayoutChanges',
        toolbarButtons: [
          {
            label: `Undo Layout Changes`,
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              undoLayoutChanges(adaptableApi);
            },
            buttonStyle: {
              variant: 'raised',
              tone: 'warning',
            },
          },
        ],
        title: 'Undo Unsaved Changes',
      },
      {
        name: 'ResetLayoutChanges',
        toolbarButtons: [
          {
            label: `Reset Layout Changes`,
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              resetLayoutChanges(adaptableApi);
            },
            buttonStyle: {
              variant: 'raised',
              tone: 'error',
            },
          },
        ],
        title: 'Reset to Initial State',
      },
    ],
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_button, context) => {
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Default',
          Toolbars: [
            'Layout',
            'PersistLayoutChanges',
            'UndoLayoutChanges',
            'ResetLayoutChanges',
          ],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-github_stars',
          Rule: '[github_stars] > 1000',
          Style: {
            BackColor: 'var(--ab-color-palette-21)',
            ForeColor: 'var(--ab-color-palette-13)',
          },
          Scope: {
            ColumnIds: ['github_stars'],
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'language',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
        },
        {
          Name: 'Grouped Layout',
          RowGroupedColumns: ['language'],
          TableColumns: [
            'name',
            'github_stars',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          RowGroupValues: {
            RowGroupDefaultBehavior: 'collapsed',
          },
        },
      ],
    },
  },
};
```

**`src/stateOptions.ts`**

```ts
import {
  AdaptableApi,
  AdaptablePersistentState,
  AdaptableStateFunctionConfig,
  LayoutChangedInfo,
  LayoutState,
  StateOptions,
} from '@adaptabletools/adaptable';

// in a real application, you would probably keep this in your application state
let LAST_PERSISTED_LAYOUT_STATE: LayoutState;

export const customStateOptions: StateOptions = {
  persistState: (state, adaptableStateFunctionConfig) => {
    const {adaptableStateKey} = adaptableStateFunctionConfig;

    // Layout changes stay local until Persist ALL / CURRENT Layout Changes is clicked.
    // Other objects (e.g. Format Column) still auto-save.
    state.Layout = LAST_PERSISTED_LAYOUT_STATE;

    persistStateInLocalStorage(adaptableStateKey, state);

    return Promise.resolve(true);
  },
  loadState: (config: AdaptableStateFunctionConfig) => {
    return new Promise(resolve => {
      let state = {};
      try {
        state =
          JSON.parse(
            localStorage.getItem(config.adaptableStateKey) as string
          ) || {};
      } catch (err) {
        console.log('Error loading state', err);
      }

      resolve(state);
    });
  },
};

export function updateLastPersistedLayoutState(state: LayoutState) {
  LAST_PERSISTED_LAYOUT_STATE = state;
}

export function persistAllLayoutChanges(adaptableApi: AdaptableApi) {
  console.log(`Persisting ALL Layout Changes!`);

  const adaptablePersistentState = adaptableApi.stateApi.getPersistentState();
  const adaptableStateKey = adaptableApi.optionsApi.getAdaptableStateKey();
  persistStateInLocalStorage(adaptableStateKey, adaptablePersistentState);

  updateLastPersistedLayoutState(adaptablePersistentState.Layout);
}

export function persistCurrentLayoutChanges(adaptableApi: AdaptableApi) {
  console.log(`Persisting CURRENT Layout Changes!`);

  const adaptablePersistentState = adaptableApi.stateApi.getPersistentState();
  const currentLayoutName = adaptablePersistentState.Layout.CurrentLayout;
  const currentLayout = adaptablePersistentState.Layout.Layouts.find(
    layout => layout.Name === currentLayoutName
  );

  if (!currentLayout) {
    return;
  }

  const layouts = [...LAST_PERSISTED_LAYOUT_STATE.Layouts];
  const layoutIndex = layouts.findIndex(
    layout => layout.Name === currentLayout.Name
  );
  if (layoutIndex === -1) {
    layouts.push(currentLayout);
  } else {
    layouts[layoutIndex] = currentLayout;
  }

  updateLastPersistedLayoutState({
    ...LAST_PERSISTED_LAYOUT_STATE,
    CurrentLayout: currentLayoutName,
    Layouts: layouts as LayoutState['Layouts'],
  });

  persistStateInLocalStorage(adaptableApi.optionsApi.getAdaptableStateKey(), {
    ...adaptablePersistentState,
    Layout: LAST_PERSISTED_LAYOUT_STATE,
  });
}

/**
 * When the user switches away from a Layout, discard its unsaved changes by
 * restoring the version from the last persisted snapshot. Layouts which are
 * not in the snapshot (e.g. a freshly cloned Layout) are left untouched.
 */
function revertAbandonedLayoutChanges(
  adaptableApi: AdaptableApi,
  abandonedLayoutName: string
) {
  const persistedLayout = LAST_PERSISTED_LAYOUT_STATE.Layouts.find(
    layout => layout.Name === abandonedLayoutName
  );
  if (!persistedLayout) {
    return;
  }

  const runningLayout = adaptableApi.layoutApi.getLayoutByName(
    abandonedLayoutName
  );
  if (
    !runningLayout ||
    JSON.stringify(runningLayout) === JSON.stringify(persistedLayout)
  ) {
    return;
  }

  adaptableApi.layoutApi.createOrUpdateLayout(persistedLayout);
}

export function onLayoutChanged(
  adaptableApi: AdaptableApi,
  layoutChangedInfo: LayoutChangedInfo
) {
  if (layoutChangedInfo.actionName !== 'LAYOUT_SELECT') {
    return;
  }

  const abandonedLayoutName = layoutChangedInfo.oldLayoutState?.CurrentLayout;
  if (
    !abandonedLayoutName ||
    abandonedLayoutName === layoutChangedInfo.newLayoutState.CurrentLayout
  ) {
    return;
  }

  // defer so we don't dispatch a state update while the select action is processed
  setTimeout(() => {
    revertAbandonedLayoutChanges(adaptableApi, abandonedLayoutName);
  }, 0);
}

export function undoLayoutChanges(adaptableApi: AdaptableApi) {
  console.log(`Undo Unsaved Layout Changes!`);
  const stateApi = adaptableApi.stateApi;

  const adaptablePersistentState = stateApi.getPersistentState();

  adaptablePersistentState.Layout = LAST_PERSISTED_LAYOUT_STATE;

  stateApi.reloadInitialState(adaptablePersistentState);
}

export function resetLayoutChanges(adaptableApi: AdaptableApi) {
  console.log(`Reset Layout to Initial State!`);
  const stateApi = adaptableApi.stateApi;

  const adaptablePersistentState = stateApi.getPersistentState();

  // Reset the Layout state to the initial state
  const initialLayoutState: LayoutState = stateApi.getInitialState().Layout;

  adaptablePersistentState.Layout = initialLayoutState;
  updateLastPersistedLayoutState(initialLayoutState);

  stateApi.reloadInitialState(adaptablePersistentState);
}

export function persistStateInLocalStorage(
  adaptableStateKey: string,
  state: AdaptablePersistentState
) {
  console.log(`Persisting state!`);
  localStorage.setItem(adaptableStateKey, JSON.stringify(state));
}
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {onLayoutChanged, updateLastPersistedLayoutState} from './stateOptions';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  updateLastPersistedLayoutState(adaptableApi.layoutApi.getLayoutState());

  adaptableApi.eventApi.on('LayoutChanged', layoutChangedInfo =>
    onLayoutChanged(adaptableApi, layoutChangedInfo)
  );
};
```
