# Custom Toolbars

Canonical page: https://www.adaptabletools.com/docs/ui-dashboard-custom-toolbars

- Developers are able to provide Custom Toolbars to supplement the System Toolbars shipped by AdapTable
- These are provided in Dashboard Options and can contain 3 types of content:
  - an array of AdapTable Buttons
  - an inline AdapTable Form
  - full bespoke content
- Once created, Custom Toolbars are treated as full Toolbars and can be placed in any Tab as needed

## Topics on this Page

Every Custom Toolbar is **defined** in `customToolbars` and **referenced** in Dashboard State — see [Wiring up](#wiring-up-custom-toolbars).

Choose **one or more** of these content mechanisms (they can be combined on the same toolbar):

| Content                                           | Property                         | When to use                                            |
| ------------------------------------------------- | -------------------------------- | ------------------------------------------------------ |
| [Adaptable Buttons](#providing-adaptable-buttons) | `toolbarButtons`                 | A small set of action buttons                          |
| [Inline form](#providing-an-inline-form)          | `toolbarForm`                    | Selects, inputs, and form buttons with live `formData` |
| [Bespoke content](#providing-bespoke-content)     | `render` or `frameworkComponent` | Custom HTML or framework components                    |

After wiring content, see [Configuring Custom Toolbars](#configuring-custom-toolbars) for **Close** / **Configure** actions and events.

Custom Toolbars allow developers to provide their own bespoke content inside the AdapTable Dashboard.

- Custom Toolbars are treated the same as [Module Toolbars](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md) and can be Pinned or placed in named Tabs
- AdapTable will take care of ensuring the Toolbar displays / renders when it needs to

They are provided in the `customToolbars` section of [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md)

### The Custom Toolbar object

The [`CustomToolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [frameworkComponent](https://www.adaptabletools.com/docs/reference/customtoolbar.md#frameworkcomponent) | [`AdaptableFrameworkComponent`](https://www.adaptabletools.com/docs/reference/adaptableframeworkcomponent.md) | The Framework-specific (Angular, React or Vue) component to be rendered |
| [name](https://www.adaptabletools.com/docs/reference/customtoolbar.md#name) | `string` | How Toolbar is referenced (e.g. in Dashboard Popup when managing toolbars) |
| [onToolbarFormChange](https://www.adaptabletools.com/docs/reference/customtoolbar.md#ontoolbarformchange) | `(formData: TData, context: `[`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md)`<TData>) => void` | Callback invoked whenever the user changes a value in the toolbar form |
| [render](https://www.adaptabletools.com/docs/reference/customtoolbar.md#render) | `(customRenderContext: `[`CustomRenderContext`](https://www.adaptabletools.com/docs/reference/customrendercontext.md)`) => string \| null` | Function to provide custom content when NOT using a Framework wrapper |
| [title](https://www.adaptabletools.com/docs/reference/customtoolbar.md#title) | `string` | Title to display in Toolbar; if unset or empty string, nothing will show |
| [toolbarActions](https://www.adaptabletools.com/docs/reference/customtoolbar.md#toolbaractions) | [`ToolbarActions`](https://www.adaptabletools.com/docs/reference/toolbaractions.md) | Actions available in a Custom Dashboard Toolbar |
| [toolbarButtons](https://www.adaptabletools.com/docs/reference/customtoolbar.md#toolbarbuttons) | [`AdaptableButton`](https://www.adaptabletools.com/docs/reference/adaptablebutton.md)`<`[`CustomToolbarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md)`>[]` | Optional set of buttons to show in the Toolbar |
| [toolbarForm](https://www.adaptabletools.com/docs/reference/customtoolbar.md#toolbarform) | [`AdaptableForm`](https://www.adaptabletools.com/docs/reference/adaptableform.md)`<`[`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md)`<TData>, TData>` | Optional inline form to render in the Toolbar (e.g. selects, checkboxes,<br/>inputs).<br/><br/>Use this when you want to expose interactive controls - rather than just<br/>buttons - in your Custom Toolbar without resorting to bespoke `render`<br/>or `frameworkComponent` content.<br/><br/>The form&#39;s `fields` are rendered side-by-side using the `inline` form<br/>layout. When the user changes any value the <br/>callback is invoked. Buttons declared on the form receive a<br/> which includes the current `formData`. |

## Wiring Up Custom Toolbars

Custom Toolbars are provided in a 2-step process:

1. The Custom Toolbar is **defined** in `customToolbars` in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md)
2. The Custom Toolbar is **referenced** in [Dashboard Initial State](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md)

### Wiring up a Custom Toolbar

These are the 2 steps required to provide a Custom Toolbar in AdapTable.

Create Custom Toolbar in `customToolbars` property in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

Add 2 descriptive properties:

- `name` - how the Toolbar is internally referenced in AdapTable
- `title` - how the Toolbar is referenced in the AdapTable UI

Add the content (one or more of):

- AdapTable Buttons
- inline AdapTable Form
- Bespoke rendering

```tsx {3}
const adaptableOptions: AdaptableOptions = {
  dashboardOptions: {
    customToolbars: [
      {
        name: 'buttons_toolbar',
        title: 'Buttons',
        toolbarButtons: [ // content here ],
      },
      {
        name: 'form_toolbar',
        title: 'Form',
        toolbarForm: { // content here },
      },
      {
        name: 'bespoke_toolbar',
        title: 'Bespoke',
        frameworkComponent: { // content here },
      },
    ],
  },
};
```

Reference the Custom Toolbar in AdapTable's [Dashboard](https://www.adaptabletools.com/docs/ui-dashboard/index.md).

Use the value supplied as the `name` property in Dashboard Options:

Set the Custom Toolbar either as a [Dashboard Tab](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md#tabs) or a [Pinned Toolbar](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md#pinned-toolbars)

```ts {3}
initialState: {
  Dashboard: {
    PinnedToolbars: ['buttons_toolbar', 'form_toolbar', 'bespoke_toolbar'],
  }
}
```

## Custom Toolbar Contents

Essentially, three different types of content can be displayed in a Custom Toolbar:

| Content type                                  | Description                                                                                                |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| [Buttons](#providing-adaptable-buttons)       | A simple array of [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) |
| [Inline Form](#providing-an-inline-form)      | Declarative form controls (selects, checkboxes, inputs) rendered side-by-side                              |
| [Bespoke content](#providing-bespoke-content) | For when more than buttons or form controls are required                                                   |

- Each Custom Toolbar contains separate _div_ elements - one for each method of providing content
- This means that all 3 mechanisms can be combined freely on the same Toolbar

### Which One Do I Use?

Use this quick-reference to pick the right content for your needs:

| You want to render…                              | Use                                                |
| ------------------------------------------------ | -------------------------------------------------- |
| A small set of action buttons                    | `toolbarButtons`                                   |
| Form components (with or without buttons)        | `toolbarForm`                                      |
| Buttons which need to read form's current values | `toolbarForm.buttons` (`context` has `formData`)   |
| More complex UI (e.g. framework component, HTML) | Bespoke Content (`render` or `frameworkComponent`) |

### Buttons vs Form Buttons

From a UI point of view `toolbarButtons` and `toolbarForm.buttons` look identical.

The key difference between them is the `context` they receive:

- `toolbarButtons` get a [`CustomToolbarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md)
- `toolbarForm.buttons` get a [`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md) which additionally carries the live `formData`

All three mechanisms can coexist on the same Toolbar.

For instance you can place a form on the left and a couple of action buttons on the right.

## Providing AdapTable Buttons

In this option, you simply provide an array of [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) to be displayed in the `toolbarButtons` property of [`Custom Toolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md).

If you require just to display a few buttons in the Custom Toolbar then use this option

- If your buttons need to read values from a Toolbar Form (e.g. an "Apply" button that reads the current select value) put them in `toolbarForm.buttons` instead - the `context` passed to those buttons is a [`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md) which carries the live `formData`
- Buttons declared in `toolbarButtons` only ever receive a [`CustomToolbarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md) with no `formData`
- See [Providing an Inline Form](#providing-an-inline-form) below

### Providing Custom Buttons

Supply an array of [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) on the `toolbarButtons` property.

Each button's `label`, `onClick`, and other callbacks receive a [`CustomToolbarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md) with `adaptableApi` and the hosting toolbar — but no form data.

```ts {6}
dashboardOptions: {
  customToolbars: [
    {
      name: 'ButtonToolbar',
      title: 'Buttons',
      toolbarButtons: [
        {
          label: (button, context) =>
            context.adaptableApi.themeApi.getCurrentTheme() === 'light'
              ? 'Switch to Dark Theme'
              : 'Switch to Light Theme',
          onClick: (button, context) => {
            const themeApi = context.adaptableApi.themeApi;
            themeApi.getCurrentTheme() === 'light'
              ? themeApi.loadDarkTheme()
              : themeApi.loadLightTheme();
          },
          buttonStyle: {tone: 'accent', variant: 'raised'},
        },
        {
          label: () => 'Show Date',
          onClick: (button, context) => {
            context.adaptableApi.alertApi.showAlertInfo(
              'Current Date',
              'Today is: ' + new Date().toLocaleDateString(),
            );
          },
        },
      ],
    },
  ],
},
```

### Configuring Custom Toolbar Buttons

As with all Adaptable Buttons, the button can be styled to user requirements with many properties and functions available to configure visibility, styling, onClick and other features.

- See the [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) for full details on configuring buttons

All the Button's functions receive as context a bespoke [`CustomToolBarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md) object which is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [customToolbar](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md#customtoolbar) | [`CustomToolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) | Custom Toolbar which hosts the Button |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**Example: Custom Toolbar: Using Buttons**

Providing Custom Toolbars with AdapTable Buttons

- In this example we create a Custom Toolbar - `Buttons` - which contains 2 AdapTable Buttons (which have been given different styles):
  - Switch Theme - the Text (and click action) changes based on the Current Theme
  - Show Date - shows todays's date as a notification; the label updates every second to display the current time

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 {
  AdaptableButton,
  AdaptableOptions,
  CustomToolbarButtonContext,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar With Buttons',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'ButtonToolbar',
        title: 'Buttons',
        toolbarActions: [],
        toolbarButtons: [
          {
            label: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              return context.adaptableApi.themeApi.getCurrentTheme() == 'light'
                ? 'Switch to Dark Theme'
                : 'Switch to Light Theme';
            },

            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              context.adaptableApi.themeApi.getCurrentTheme() == 'light'
                ? context.adaptableApi.themeApi.loadDarkTheme()
                : context.adaptableApi.themeApi.loadLightTheme();
            },
            buttonStyle: {
              tone: 'accent',
              variant: 'raised',
            },
          },
          {
            label: () => {
              return 'Show Date at: ' + new Date().toLocaleTimeString();
            },
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              context.adaptableApi.alertApi.showAlertInfo(
                'Current Date',
                'Today is: ' + new Date().toLocaleDateString()
              );
            },
            buttonStyle: {
              tone: 'info',
              variant: 'text',
            },
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Custom Tab',
          Toolbars: ['ButtonToolbar'],
        },
      ],
    },

    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  setInterval(() => {
    adaptableApi.dashboardApi.refreshDashboard();
  }, 1000);
};
```

### Automating Buttons

A common use case is for the AdapTable Buttons in a Custom Toolbar to be created dynamically.

For instance a user might want to render a button for each [Named Query](https://www.adaptabletools.com/docs/handbook-named-queries/index.md) that is available.

- The [Dashboard API](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md) contains functions that enable Custom Toolbars to be accessed and easily updated
- Listen to the [Adaptable State Changed](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-events/index.md) Event to be updated when objects change in [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md)

If you have changed a Toolbar progromatically, call `refreshDashboard` in [Dashboard API](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md) to update the UI

**Example: Custom Toolbar: Automating Buttons**

Custom Toolbars with dynamic AdapTable Buttons

- This demo contains a (pinned) Custom Toolbar displaying a Button for each [Named Query](https://www.adaptabletools.com/docs/handbook-named-queries/index.md) in [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md); when clicked, it sets the [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md) to that Query
- We provide 3 Named Queries in [Named Query Initial State](https://www.adaptabletools.com/docs/technical-reference-named-query/index.md) - `JavaScript`, `Big Stars`, `Top Frameworks` - and the demo renders a button for each (together with a Clear Filter Button)
- Additional buttons will be created / removed as Queries are manipulated in the UI - achieved by listening to the [Adaptable State Changed Event](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-events/index.md)

- Create a new Named Query and then click the new Button that is dynamically created to run the Expression as a Grid Filter
- Click one of the Buttons and then edit the associated Named Query in the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md) - note that the the filter automatically updates

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: 'Custom Toolbar With Automated Buttons',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'QueryToolbar',
        toolbarButtons: [],
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['NamedQuery'],
      PinnedToolbars: ['QueryToolbar', 'GridFilter'],
    },
    NamedQuery: {
      NamedQueries: [
        {
          Name: 'JavaScript',
          Expression: '[language]="JavaScript"',
        },
        {
          Name: 'Top Frameworks',
          Expression: '[name] IN ("react", "angular", "vue")',
        },
        {
          Name: 'Big Stars',
          Expression: '[github_stars]> 50000',
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {
  AdaptableApi,
  AdaptableButton,
  AdaptableReadyInfo,
  AdaptableStateChangedInfo,
  CustomToolbarButtonContext,
  NamedQuery,
} from '@adaptabletools/adaptable';

// Function which creates the Toolbar Buttons
const createNameQueryToolbarButtons = function (adaptableApi: AdaptableApi) {
  const queryToolbar = adaptableApi.optionsApi
    .getDashboardOptions()
    .customToolbars?.find(t => t.name == 'QueryToolbar');
  if (queryToolbar && queryToolbar.toolbarButtons) {
    const allqueries: NamedQuery[] =
      adaptableApi.namedQueryApi.getNamedQueries();
    const toolbarButtons: AdaptableButton<CustomToolbarButtonContext>[] = [];

    // Add one Button for each Named Query
    allqueries.forEach((namedQuery: NamedQuery) => {
      const toolbarButton: AdaptableButton<CustomToolbarButtonContext> = {
        label: namedQuery.Name,
        onClick: () => {
          adaptableApi.filterApi.gridFilterApi.setGridFilterExpression(
            `QUERY("${namedQuery.Name}")`
          );
        },
        buttonStyle: {
          tone: 'info',
          variant: 'outlined',
        },
      };
      toolbarButtons.push(toolbarButton);
    });

    // Add a Clear Filter button (disabled if no Queries present)
    const clearQueriesToolbarButton: AdaptableButton<CustomToolbarButtonContext> =
      {
        label: 'Clear Filter',
        onClick: () => {
          adaptableApi.filterApi.gridFilterApi.clearGridFilter();
        },
        disabled: () => {
          return allqueries.length < 1;
        },
        buttonStyle: {
          tone: 'none',
          variant: 'outlined',
        },
      };
    toolbarButtons.push(clearQueriesToolbarButton);

    // Add the Buttons to the Toolbar
    queryToolbar.toolbarButtons.length = 0;
    queryToolbar.toolbarButtons.push(...toolbarButtons);

    // Referesh the Dashboard and re-apply Grid Filtering
    adaptableApi.dashboardApi.refreshDashboard();
    adaptableApi.gridApi.applyFiltering();
  }
};

// In Adaptable Ready Event and call function to create Buttons, and set up Adaptable State listener
export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  // Call the function now AdapTable is ready to create Dashboard Buttons
  createNameQueryToolbarButtons(adaptableApi);

  // Listen to State Changed and re-create Dashboard Buttons if Named Query state changes
  adaptableApi.eventApi.on(
    'AdaptableStateChanged',
    (stateChangedInfo: AdaptableStateChangedInfo) => {
      if (stateChangedInfo.action.type.includes('NAMED_QUERY')) {
        createNameQueryToolbarButtons(adaptableApi);
      }
    }
  );
};
```

## Providing an Inline Form

If you need more than just buttons - for instance a select, a checkbox or a text input - you can configure an **inline form** on your Custom Toolbar via the `toolbarForm` property.

This is an [Adaptable Form](https://www.adaptabletools.com/docs/ui-tutorial-configuring-adaptable-forms/index.md) (also used by Alerts and Export Custom Destinations) which renders the fields in a compact, horizontal `inline` layout that is well-suited to a Toolbar.

Forms expose interactive controls (e.g. selects, inputs) without writing bespoke `render` / `frameworkComponent` content

The shape of `toolbarForm` is the same `AdaptableForm` as used elsewhere:

```ts
toolbarForm?: AdaptableForm<CustomToolbarFormContext>;

onToolbarFormChange?: (
  formData: AdaptableFormData,
  context: CustomToolbarFormContext,
) => void;
```

- `fields` - array of [`AdaptableFormField`](https://www.adaptabletools.com/docs/reference/adaptableformfield.md) definitions
- `buttons` - optional [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) (e.g. an "Apply" or "Clear" button); each button receives a [`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md) which includes the current `formData`
- `onToolbarFormChange` - optional callback invoked whenever any field value changes; useful when you want a single hook for all form changes
- Each individual field can also declare an `onValueChange` callback for control-level reactions (e.g. apply a filter the moment the select changes); see **Reacting per-field** in the DevSteps below

### Providing an AdapTable Form

Use this workflow after you have created the toolbar shell in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md) — see [Wiring Up Custom Toolbars](#wiring-up-custom-toolbars) for `name`, `title`, and Dashboard visibility.

Set `toolbarForm` on your [`Custom Toolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) with a `fields` array of [`AdaptableFormField`](https://www.adaptabletools.com/docs/reference/adaptableformfield.md) definitions.

AdapTable renders them in a compact horizontal (`inline`) [`AdaptableFormLayout`](https://www.adaptabletools.com/docs/reference/adaptableformlayout.md) — you do not need to set the layout manually.

Optionally add [Adaptable Buttons](https://www.adaptabletools.com/docs/ui-tutorial-displaying-adaptable-buttons/index.md) on `toolbarForm.buttons`.

Each button receives a [`CustomToolbarFormContext`](https://www.adaptabletools.com/docs/reference/customtoolbarformcontext.md) which extends [`CustomToolbarButtonContext`](https://www.adaptabletools.com/docs/reference/customtoolbarbuttoncontext.md) with the current `formData` keyed by field `name`.

You can also set `onToolbarFormChange` on the [`Custom Toolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) to react whenever any field value changes.

Each field can declare an `onValueChange` callback that fires only when **that specific field** changes.

This suits "live" toolbars — a select narrows the grid filter on change, a checkbox toggles a row style, and so on — without an Apply button.

- Use `onValueChange` (per-field) for control-level reactions
- Use `onToolbarFormChange` (form-level) when one hook should handle any change, or when several fields combine to drive one action
- Both can be used together — both fire for the same change

A Clear button often needs to wipe derived state (e.g. the grid filter) **and** reset the form values. Call `resetCustomToolbarFormData` on [`DashboardApi`](https://www.adaptabletools.com/docs/reference/dashboardapi.md) instead of manually mirroring each field's `defaultValue`.

`resetCustomToolbarFormData(name?)` rolls every field back to its `defaultValue` and fires `onToolbarFormChange` once. Omit `name` to reset every Custom Toolbar that hosts a `toolbarForm`.

```ts [[1, 6, "toolbarForm"], [2, 32, "buttons"], [2, 36, "formData"], [2, 51, "onToolbarFormChange"], [3, 18, "onValueChange"], [4, 44, "resetCustomToolbarFormData"]]
dashboardOptions: {
  customToolbars: [
    {
      name: 'FormToolbar',
      title: 'Filter By',
      toolbarForm: {
        fields: [
          {
            name: 'language',
            label: 'Language',
            fieldType: 'select',
            defaultValue: 'All',
            options: [
              {label: 'All', value: 'All'},
              {label: 'TypeScript', value: 'TypeScript'},
              {label: 'Python', value: 'Python'},
            ],
            onValueChange: (value, context) => {
              const ctx = context as CustomToolbarFormContext;
              ctx.adaptableApi.filterApi.gridFilterApi.setGridFilterExpression(
                value && value !== 'All' ? `[language] = "${value}"` : null,
              );
            },
          },
          {
            name: 'onlyPopular',
            label: 'Popular Only',
            fieldType: 'checkbox',
            defaultValue: false,
          },
        ],
        buttons: [
          {
            label: 'Apply',
            onClick: (button, context) => {
              const {language, onlyPopular} = context.formData;
              // ...do something with the values
            },
          },
          {
            label: 'Clear',
            onClick: (_button, context) => {
              context.adaptableApi.filterApi.gridFilterApi.clearGridFilter();
              context.adaptableApi.dashboardApi.resetCustomToolbarFormData(
                'FormToolbar',
              );
            },
          },
        ],
      },
      onToolbarFormChange: (formData, context) => {
        // Optional — invoked when any field changes
      },
    },
  ],
},
```

**Example: Custom Toolbar: Inline Form**

Providing Custom Toolbars with declarative form controls reacting per-field

- This demo contains a Custom Toolbar - `Filter By` - which exposes 2 controls and 1 button:
  - A **Language** select - filters by `language` column when changed
  - A **Popular Only** checkbox - additionally filters to rows with `github_stars > 50000`
  - A **Clear** button - clears the [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md)
- Each control uses `onValueChange` so the Grid Filter updates immediately on change - no Apply button required

- Pick a Language from the select - the grid filters as soon as it changes
- Toggle the Popular Only checkbox - the filter recomputes and combines both clauses
- Click Clear to reset the Grid Filter

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  [template]
  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,
  CustomToolbarFormContext,
} from '@adaptabletools/adaptable';
import { WebFramework } from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar With Form',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'FormToolbar',
        title: 'Filter By',
        toolbarActions: [],
        // Inline form controls rendered directly in the Toolbar.
        // Each field can declare its own `onValueChange` handler so that
        // controls react immediately, with no need for an Apply button.
        toolbarForm: {
          fields: [
            {
              name: 'language',
              label: 'Language',
              fieldType: 'select',
              defaultValue: 'All',
              options: [
                { label: 'All', value: 'All' },
                { label: 'JavaScript', value: 'JavaScript' },
                { label: 'TypeScript', value: 'TypeScript' },
                { label: 'Python', value: 'Python' },
                { label: 'Go', value: 'Go' },
              ],
              // Filter immediately as the select changes.
              // `ctx.formData` always reflects the latest values, including
              // the field that just changed - so we can read straight from it.
              onValueChange: (_value, context) =>
                applyFilter(context as CustomToolbarFormContext),
            },
            {
              name: 'onlyPopular',
              label: 'Popular Only',
              fieldType: 'checkbox',
              defaultValue: false,
              onValueChange: (_value, context) =>
                applyFilter(context as CustomToolbarFormContext),
            },
          ],
          buttons: [
            {
              label: 'Clear',
              buttonStyle: { tone: 'neutral', variant: 'text' },
              onClick: (
                button: AdaptableButton<CustomToolbarFormContext>,
                context: CustomToolbarFormContext
              ) => {
                context.adaptableApi.filterApi.gridFilterApi.clearGridFilter();
              },
            },
          ],
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Custom Tab',
          Toolbars: ['FormToolbar'],
        },
      ],
    },
    Theme: { CurrentTheme: 'dark' },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};

function applyFilter(context: CustomToolbarFormContext) {
  const { language, onlyPopular } = context.formData;
  const expressions: string[] = [];
  if (language && language !== 'All') {
    expressions.push(`[language] = "${language}"`);
  }
  if (onlyPopular) {
    expressions.push(`[github_stars] > 50000`);
  }
  // setGridFilterExpression accepts a falsy value to clear the filter
  context.adaptableApi.filterApi.gridFilterApi.setGridFilterExpression(
    expressions.join(' AND ') || null
  );
}
```

### Form Field Types

A Custom Toolbar form supports every [`AdaptableFormFieldType`](https://www.adaptabletools.com/docs/reference/adaptableformfieldtype.md):

| `fieldType`  | Renders as                                 | Typical use in a Toolbar                                    |
| ------------ | ------------------------------------------ | ----------------------------------------------------------- |
| `text`       | Single-line text input                     | Free-text search (e.g. `CONTAINS([name], …)`)               |
| `textarea`   | Multi-line text input                      | Longer search prompts / comments                            |
| `number`     | Numeric input (with shortcuts)             | Threshold filters (e.g. `[stars] > N`)                      |
| `slider`     | Range slider with inline value read-out    | Numeric thresholds you'd rather drag than type              |
| `date`       | Native HTML5 date picker                   | Date-range filters                                          |
| `time`       | Time-of-day picker (`HH:mm`)               | Time-of-day filters                                         |
| `datetime`   | Combined date + time picker                | Precise timestamp filters                                   |
| `color`      | Native HTML5 colour picker                 | Filter by tag colour, etc.                                  |
| `select`     | Combobox with the supplied options         | Categorical filters (e.g. language, status, currency)       |
| `radio`      | Inline group of mutually-exclusive options | Small enums (e.g. sort direction, density)                  |
| `checkbox`   | Checkbox                                   | Boolean toggles (e.g. "Has Wiki", "Show Archived")          |
| `textOutput` | Read-only inline label                     | Static guidance / computed labels alongside other fields    |
| `custom`     | Anything you render via `render`           | Bespoke widgets - star ratings, tag editors, swatch pickers |

**Example: Custom Toolbar: All Field Types**

A single Custom Toolbar exercising every supported AdaptableFormFieldType plus validation, helpText, tooltips, conditional visibility and form-validity-aware buttons

- This demo contains a Custom Toolbar - `Filters` - with one field of every type:
  - **Name** (`text`) - filters via `CONTAINS([name], …)`. Has a `placeholder`, `helpText` ("min 2 characters"), a label `tooltip`, and a custom `validate` that requires at least 2 chars
  - **Min Stars** (`number`) - adds `[github_stars] > N`. Uses `min`, `max` and `step`
  - **Created After** (`date`) - adds `[created_at] >= DATE("…")`. Has a label `tooltip`
  - **Language** (`select`) - adds `[language] = "…"`
  - **Has Wiki** (`checkbox`) - adds `[has_wiki] = TRUE`
  - **Min Watchers** (`number`) - **conditionally shown** via `hidden: (formData) => !formData.onlyHasWiki`; only appears when "Has Wiki" is ticked
  - **Tip** (`textOutput`) - read-only inline guidance
- Each control's `onValueChange` calls a shared `applyFilter` helper which combines all active clauses with `AND` and pushes the result via `setGridFilterExpression`
- An **Apply** button gates on `context.formIsValid` - while any field is invalid (e.g. a 1-character name) the button stays disabled

- Type just one character into Name - the inline error appears and the Apply button disables
- Bump Min Stars up to e.g. `10000` to narrow the result set
- Pick a Language and tick Has Wiki - the **Min Watchers** field appears
- Untick Has Wiki to make the conditional field disappear again
- Clear any field (e.g. set Min Stars back to `0`) to drop just that clause

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  [template]
  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,
  CustomToolbarFormContext,
} from '@adaptabletools/adaptable';
import { WebFramework } from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar Field Types',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'AllFieldTypesToolbar',
        title: 'Filters',
        toolbarActions: [],
        // A Custom Toolbar that exercises every supported AdaptableFormFieldType
        // AND the Tier-1 form features: required, validate, helpText, tooltip,
        // placeholder, hidden/disabled.
        toolbarForm: {
          fields: [
            // 1) `text` field with placeholder, helpText and a custom validate
            {
              name: 'nameContains',
              label: 'Name',
              fieldType: 'text',
              defaultValue: '',
              placeholder: 'e.g. react',
              helpText: 'min 2 characters',
              tooltip: 'Free-text search on repository name',
              validate: (value) => {
                if (value && String(value).length < 2) {
                  return 'Enter at least 2 characters';
                }
                return null;
              },
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 2) `number` field - required, with min/max
            {
              name: 'minStars',
              label: 'Min Stars',
              fieldType: 'number',
              defaultValue: 0,
              min: 0,
              max: 1000000,
              step: 1000,
              placeholder: '0',
              helpText: 'between 0 and 1,000,000',
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 3) `date` field - tooltip on the label
            {
              name: 'createdAfter',
              label: 'Created After',
              fieldType: 'date',
              defaultValue: '',
              tooltip: 'Earliest creation date to include',
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 4) `select` field
            {
              name: 'language',
              label: 'Language',
              fieldType: 'select',
              defaultValue: 'All',
              options: [
                { label: 'All', value: 'All' },
                { label: 'JavaScript', value: 'JavaScript' },
                { label: 'TypeScript', value: 'TypeScript' },
                { label: 'Python', value: 'Python' },
                { label: 'Go', value: 'Go' },
              ],
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 5) `checkbox` field - drives visibility of the next field
            {
              name: 'onlyHasWiki',
              label: 'Has Wiki',
              fieldType: 'checkbox',
              defaultValue: false,
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 6) Conditionally-shown field. Driven by the checkbox above:
            //    only visible when `onlyHasWiki === true`. A clean
            //    declarative way to "expand" the form on demand.
            {
              name: 'minWatchers',
              label: 'Min Watchers',
              fieldType: 'number',
              defaultValue: 0,
              min: 0,
              hidden: (formData) => !formData.onlyHasWiki,
              onValueChange: (_value, ctx) => applyFilter(ctx as CustomToolbarFormContext),
            },
            // 7) `textOutput` field - read-only display
            {
              name: 'info',
              label: 'Tip',
              fieldType: 'textOutput',
              defaultValue: 'all filters combine with AND',
            },
          ],
          buttons: [
            {
              label: 'Apply',
              buttonStyle: { tone: 'accent', variant: 'raised' },
              // Only enabled when the form is valid (all required + custom
              // validations pass). `formIsValid` is supplied by the form
              // automatically.
              disabled: (_button, context) => {
                const ctx = context as CustomToolbarFormContext;
                return !ctx.formIsValid;
              },
              onClick: (_button, context) =>
                applyFilter(context as CustomToolbarFormContext),
            },
          ],
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Custom Tab',
          Toolbars: ['AllFieldTypesToolbar'],
        },
      ],
    },
    Theme: { CurrentTheme: 'dark' },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_wiki',
            'created_at',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};

// Builds a Grid Filter expression from the current form values.
// `context.formData` always reflects the latest values (including the field
// that just changed), so we can read it directly.
function applyFilter(context: CustomToolbarFormContext) {
  const { nameContains, minStars, createdAfter, language, onlyHasWiki, minWatchers } =
    context.formData;
  const expressions: string[] = [];

  if (nameContains) {
    expressions.push(`CONTAINS([name], "${nameContains}")`);
  }
  if (minStars && Number(minStars) > 0) {
    expressions.push(`[github_stars] > ${minStars}`);
  }
  if (createdAfter) {
    expressions.push(`[created_at] >= DATE("${createdAfter}")`);
  }
  if (language && language !== 'All') {
    expressions.push(`[language] = "${language}"`);
  }
  if (onlyHasWiki) {
    expressions.push(`[has_wiki] = TRUE`);
  }
  if (onlyHasWiki && minWatchers && Number(minWatchers) > 0) {
    expressions.push(`[github_watchers] > ${minWatchers}`);
  }

  // setGridFilterExpression accepts a falsy value to clear the filter.
  context.adaptableApi.filterApi.gridFilterApi.setGridFilterExpression(
    expressions.join(' AND ') || null
  );
}
```

### Advanced Fields

Beyond the standard built-in field types, an `AdaptableFormField` can also be more complex, including:

- be a **multi-select** by setting `multi: true` on a `select` field - its value is then an array of selected values
- compute its `options` **dynamically** by passing a function (`(formData, context) => Option[]`)
  
  - This is useful when the choices depend on another field, or live in `adaptableApi`
  - The function can also return a `Promise` for asynchronously-loaded options

  

- be **fully bespoke** using `fieldType: 'custom'` and a `render` callback that returns any controlled React node

```ts
// multi-select
{ fieldType: 'select', multi: true, options: [...] }

// dynamic / async options
{ fieldType: 'select', options: (formData, ctx) => fetchOptionsFor(formData.region) }

// custom field
{
  fieldType: 'custom',
  render: ({ value, setValue, disabled }) => (
    <input type="range" min={0} max={100} value={value || 0}
           disabled={disabled} onChange={(e) => setValue(Number(e.target.value))} />
  ),
}
```

**Example: Custom Toolbar: Advanced Fields**

Multi-select, dependent (dynamic) options, the built-in slider and radio field types, a computed custom read-out, and Enter-to-submit

- This demo contains a Custom Toolbar - `Filters` - exercising the advanced form features:
  - **Languages** - a multi-select (`multi: true`); the filter ORs each chosen language together
  - **License** - the `options` are produced by a function that depends on the currently-selected languages, so the available licences change when you change the language selection
  - **Sort** - a `radio` group, an inline mutually-exclusive choice
  - **Min Stars** - a built-in `fieldType: 'slider'` (Tier-3 addition) - drag to change `[github_stars] > N`
  - A `fieldType: 'custom'` field reads `formData.minStars` and renders the formatted value alongside the slider, illustrating how custom renderers can read the whole form
  - The form declares `onSubmit` so pressing **Enter** while the form is valid re-applies the filter
- A **Clear** button resets the Grid Filter **and** wipes the toolbar form's own values via `dashboardApi.resetCustomToolbarFormData(...)`

- Pick two or three Languages from the multi-select - the filter combines them with OR
- Watch the License options change when you change the language selection
- Drag the Min Stars slider - the filter and the displayed value update live
- Press Enter inside any field to re-submit; click Clear to wipe both the filter and the toolbar form

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  [template]
  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 * as React from 'react';
import {
  AdaptableFormFieldRenderParams,
  AdaptableOptions,
  CustomToolbar,
  CustomToolbarFormContext,
} from '@adaptabletools/adaptable';
import { WebFramework } from './rowData';

type AdvancedToolbarFormData = {
  languages: string[];
  license: string;
  sort: string;
  minStars: number;
  minStarsLabel: string;
};

const advancedFormToolbar: CustomToolbar<AdvancedToolbarFormData> = {
  name: 'AdvancedFormToolbar',
  title: 'Filters',
  toolbarActions: [],
        // Showcases Tier-2 + Tier-3 form features:
        //   - multi-select (`multi: true`)
        //   - dynamic options (function form, optionally async)
        //   - the built-in `slider` field type
        //   - `radio` mutually-exclusive option group
        //   - a `custom` field reading from form data (computed read-out)
        //   - form-level `onSubmit` (Enter-to-submit)
        toolbarForm: {
          layout: 'inline',
          // Pressing Enter inside any field submits the form when valid.
          // Here we just route Enter through the same applyFilter helper.
          onSubmit: (_formData, context) => applyFilter(context),
          fields: [
            // 1) multi-select: pick any combination of languages
            {
              name: 'languages',
              label: 'Languages',
              fieldType: 'select',
              multi: true,
              defaultValue: [],
              placeholder: 'all',
              options: [
                { label: 'JavaScript', value: 'JavaScript' },
                { label: 'TypeScript', value: 'TypeScript' },
                { label: 'Python', value: 'Python' },
                { label: 'Go', value: 'Go' },
                { label: 'Rust', value: 'Rust' },
              ],
              onValueChange: (_value, ctx) =>
                applyFilter(ctx as CustomToolbarFormContext<AdvancedToolbarFormData>),
            },
            // 2) dynamic options - License list depends on Languages
            {
              name: 'license',
              label: 'License',
              fieldType: 'select',
              defaultValue: 'All',
              options: (formData) => {
                const langs: string[] = formData.languages ?? [];
                const base = [{ label: 'All', value: 'All' }];
                if (langs.includes('JavaScript') || langs.includes('TypeScript')) {
                  base.push({ label: 'MIT', value: 'mit' });
                  base.push({ label: 'Apache-2.0', value: 'apache-2.0' });
                }
                if (langs.includes('Python') || langs.includes('Go')) {
                  base.push({ label: 'BSD-3-Clause', value: 'bsd-3-clause' });
                }
                if (langs.includes('Rust')) {
                  base.push({ label: 'MIT/Apache (Rust)', value: 'mit-apache' });
                }
                return base;
              },
              onValueChange: (_value, ctx) =>
                applyFilter(ctx as CustomToolbarFormContext<AdvancedToolbarFormData>),
            },
            // 3) radio - pick a single sort order. `radio` uses the same
            //    `options` shape as `select` but always shows every choice
            //    inline.
            {
              name: 'sort',
              label: 'Sort',
              fieldType: 'radio',
              defaultValue: 'stars',
              options: [
                { label: 'Stars', value: 'stars' },
                { label: 'Name', value: 'name' },
              ],
              onValueChange: (_value, ctx) =>
                applyFilter(ctx as CustomToolbarFormContext<AdvancedToolbarFormData>),
            },
            // 4) built-in slider (Tier 3) - replaces what used to require
            //    a custom field. Use min/max/step on the field and the form
            //    will render a controlled range input plus a tabular value
            //    read-out next to it.
            {
              name: 'minStars',
              label: 'Min Stars',
              fieldType: 'slider',
              defaultValue: 0,
              min: 0,
              max: 200000,
              step: 5000,
              helpText: 'drag to filter by github_stars',
              onValueChange: (_value, ctx) =>
                applyFilter(ctx as CustomToolbarFormContext<AdvancedToolbarFormData>),
            },
            // 5) custom field - reads from form data without owning a value
            //    of its own, illustrating that `render` always sees the
            //    full `formData`.
            {
              name: 'minStarsLabel',
              label: '',
              fieldType: 'custom',
              defaultValue: '',
              render: ({ formData }: AdaptableFormFieldRenderParams) =>
                React.createElement(
                  'span',
                  { style: { fontVariantNumeric: 'tabular-nums', minWidth: 60 } },
                  Number(formData.minStars ?? 0).toLocaleString()
                ),
            },
          ],
          buttons: [
            {
              label: 'Clear',
              buttonStyle: { tone: 'neutral', variant: 'text' },
              onClick: (_button, context) => {
                // Wipe the grid filter AND roll the toolbar form's own
                // values back to their declared defaults in a single click.
                context.adaptableApi.filterApi.gridFilterApi.clearGridFilter();
                context.adaptableApi.dashboardApi.resetCustomToolbarFormData(
                  'AdvancedFormToolbar'
                );
              },
            },
          ],
        },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar Advanced Form',
  dashboardOptions: {
    customToolbars: [advancedFormToolbar as unknown as CustomToolbar],
  },

  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Custom Tab',
          Toolbars: ['AdvancedFormToolbar'],
        },
      ],
    },
    Theme: { CurrentTheme: 'dark' },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: ['name', 'language', 'github_stars', 'license', 'created_at'],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};

function applyFilter(context: CustomToolbarFormContext<AdvancedToolbarFormData>) {
  const { languages, license, minStars } = context.formData;
  const expressions: string[] = [];

  if (Array.isArray(languages) && languages.length > 0) {
    const clauses = languages.map((l: string) => `[language] = "${l}"`).join(' OR ');
    expressions.push(`(${clauses})`);
  }
  if (license && license !== 'All') {
    expressions.push(`[license] = "${license}"`);
  }
  if (minStars && Number(minStars) > 0) {
    expressions.push(`[github_stars] > ${minStars}`);
  }

  context.adaptableApi.filterApi.gridFilterApi.setGridFilterExpression(
    expressions.join(' AND ') || null
  );
}
```

## Providing Bespoke Content

If you require to display more than just a few buttons in the Custom Toolbar or even a full AdapTable Form, there is another alternative available.

AdapTable allows you to provide full custom rendering in your Custom Toolbar.

<!-- framework: vanilla -->
### Vanilla

This is provided via the `render` property which is a JavaScript function that you provide and AdapTable will invoke as required.

The `render` function is defined as follows:

```ts
render?: (context: CustomRenderContext) => string | null;

// CustomRenderContext provides:
//   phase: 'onMount' | 'onDestroy'
//   element: HTMLDivElement
//   adaptableApi: AdaptableApi
```

On `onMount`, return an HTML string for AdapTable to inject into the toolbar. On `onDestroy`, return `null` (or omit returning content) so you can run any cleanup logic.

- Use `context.element` if you need to attach event listeners or manipulate the DOM directly after mount
- `context.adaptableApi` is available when the toolbar needs to interact with AdapTable

### Providing Bespoke Toolbar Content

Provide a function on the [`Custom Toolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) that returns the HTML string to display. This is the only content property required for a bespoke toolbar.

When [`CustomRenderContext`](https://www.adaptabletools.com/docs/reference/customrendercontext.md) `phase` is `'onMount'`, return your markup. AdapTable inserts it into the toolbar container (`context.element`).

When `phase` is `'onDestroy'`, return `null` and perform any teardown (e.g. remove listeners you attached to `context.element`).

```ts [[1, 6, "render"], [2, 7, "onMount"], [3, 10, "return null"]]
dashboardOptions: {
  customToolbars: [
    {
      name: 'ApplicationToolbar',
      title: 'Application',
      render: (context) => {
        if (context.phase === 'onMount') {
          return '<label>Number of agents: <input type="text" /></label>';
        }
        return null;
      },
    },
  ],
},
```

**Example: Custom Toolbars: Bespoke Content**

Providing bespoke content in a Custom Toolbar

- This demo contains a Tab (entitled Custom Tab) which contains 2 Custom Toolbars with custom rendering:
  - `Hello World` - just contains text
  - `Bespoke Rendering` - contains an input

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  [template]
  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 {CustomRenderContext} from '@adaptabletools/adaptable';
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar Rendered Content',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'hellowWorldToolbar',
        title: 'Hello World Example',
        render: () => {
          return '<div><label>Hello World!!!</label> </div>';
        },
      },
      {
        name: 'BespokeRenderingToolbar',
        title: 'Bespoke Rendering',
        render: (customRenderContext: CustomRenderContext) => {
          if (customRenderContext.phase == 'onMount') {
            return `
              <label>Number of agents: <input type="text" /></label>
            `;
          }
          return null;
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Custom Tab',
          Toolbars: ['hellowWorldToolbar', 'BespokeRenderingToolbar'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

<!-- /framework -->

<!-- framework: angular -->
### Angular

When using AdapTable Angular, bespoke toolbar content is provided via the `frameworkComponent` property in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

- This is only required if you wish to provide **bespoke Angular component(s)** in the Custom Toolbar
- See above on how to display Buttons or an inline Form

### Providing Bespoke Toolbar Content

In this example we are providing a SlideToggle button, which is a standard Angular Component.

The implementation that we provide is entirely generic and reusable, as the I/O params are set via the `onSetup()` function in the `frameworkComponent`.

```ts
@Component({
  selector: 'slide-toggle',
  template: `
    <label class="switch">
      <input
        class="switch-input"
        type="checkbox"
        [checked]="active"
        (change)="onToggle()" />
      <span
        class="switch-label"
        [attr.data-on]="onText"
        [attr.data-off]="offText"
        [style.background]="active ? onColor : offColor"></span>
      <span class="switch-handle"></span>
    </label>
  `,
  styles: [
    `
      // [...]
    `,
  ],
})
export class SlideToggleComponent {
  active = false;

  onText = 'ON';
  onColor = 'var(--ab-color-success)';

  offText = 'OFF';
  offColor = 'var(--ab-color-info)';

  constructor(@Inject(ADAPTABLE_API) private adaptableApi: AdaptableApi) {}

  onToggle() {
    this.active = !this.active;
    this.onChange(this.active);
  }

  onChange(toggleValue: boolean) {
    // overwritten in onSetup()
  }
}
```

Import the Component and create a Custom Toolbar definition.

In the definition do 2 things:

1. reference the Component in the `type` property (of `frameworkComponent`)

2. provide custom implementation of Component via the `onSetup()` function

```ts
const adaptableOptions: AdaptableOptions = {
  dashboardOptions: {
    customToolbars: [
      {
        name: 'LayoutToggle',
        title: 'Current layout',
        frameworkComponent: {
          type: SlideToggleComponent,
          // configure custom content & behaviour
          onSetup: ({adaptableApi}): Partial<SlideToggleComponent> => {
            return {
              onText: 'Pivot',
              offText: 'Standard',
              onChange: toggleValue => {
                if (toggleValue) {
                  adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
                } else {
                  adaptableApi.layoutApi.setLayout('Standard Layout');
                }
              },
            };
          },
        },
      },
      // [...]
    ],
  },
};
```

**Example: Angular Components: Custom Toolbars**

Providing Angular Components as Custom Toolbars

- Three Custom Toolbars: layout toggle, custom quick search, and GitHub Stars gradient toggle

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

```text
src/
  app/
    adaptableOptions.ts
    agGridModules.ts           [template]
    app.component.ts           [template]
    app.module.ts
    columnDefs.ts              [template]
    gridOptions.ts             [template]
    onAdaptableReady.ts        [template]
    quick-search.component.ts
    rowData.ts                 [template]
    slide-toggle.component.ts
    styles.css                 [template]
  index.html                   [template]
  main.ts                      [template]
  polyfills.ts                 [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#angular).

**`src/app/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable-angular-aggrid';
import {SlideToggleComponent} from './slide-toggle.component';
import {QuickSearchComponent} from './quick-search.component';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar Demo',
  dashboardOptions: {
    showQuickSearchInHeader: false,
    customToolbars: [
      {
        name: 'LayoutToggle',
        title: 'Current layout',
        frameworkComponent: {
          type: SlideToggleComponent,
          // configure custom content & behaviour
          onSetup: ({adaptableApi}): Partial<SlideToggleComponent> => {
            return {
              onText: 'Pivot',
              offText: 'Standard',
              onChange: toggleValue => {
                if (toggleValue) {
                  adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
                } else {
                  adaptableApi.layoutApi.setLayout('Standard Layout');
                }
              },
            };
          },
        },
      },
      {
        name: 'CustomQuickSearch',
        title: 'Quick Search',
        frameworkComponent: {
          type: QuickSearchComponent,
        },
      },
      {
        name: 'StyledColumnToggle',
        title: 'GitHub Stars Gradient',
        frameworkComponent: {
          type: SlideToggleComponent,
          // configure custom content & behaviour
          onSetup: ({adaptableApi}): Partial<SlideToggleComponent> => {
            return {
              active: true,
              onColor: '#a52a2a',
              offColor: 'var(--ab-color-primary-foreground)',
              onChange: toggleValue => {
                const styledColumn =
                  adaptableApi.styledColumnApi.getStyledColumnForColumnId(
                    'github_stars'
                  );
                if (toggleValue) {
                  adaptableApi.styledColumnApi.unSuspendStyledColumn(
                    styledColumn
                  );
                } else {
                  adaptableApi.styledColumnApi.suspendStyledColumn(
                    styledColumn
                  );
                }
              },
            };
          },
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Grid Configuration',
          Toolbars: [
            'LayoutToggle',
            'Layout',
            'CustomQuickSearch',
            'StyledColumnToggle',
          ],
        },
      ],
    },
    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',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
        },
        {
          Name: 'Pivot Cols Layout',
          PivotColumns: ['license'],
          PivotGroupedColumns: ['language'],
          PivotAggregationColumns: [
            {ColumnId: 'github_watchers', AggFunc: 'count'},
            {ColumnId: 'github_stars', AggFunc: 'sum'},
          ],
        },
      ],
    },
    StyledColumn: {
      StyledColumns: [
        {
          ColumnId: 'github_stars',
          Name: 'github_stars Gradient',
          GradientStyle: {
            RangeValueType: 'Number',
            CellRanges: [{Min: 'Col-Min', Max: 'Col-Max', Color: '#a52a2a'}],
          },
        },
      ],
    },
    QuickSearch: {
      CellMatchStyle: {
        BackColor: '#a1c0d4',
      },
    },
  },
};
```

**`src/app/slide-toggle.component.ts`**

```ts
import {
  ADAPTABLE_API,
  AdaptableApi,
} from '@adaptabletools/adaptable-angular-aggrid';
import {Component, Inject} from '@angular/core';

@Component({
  standalone: false,
  selector: 'slide-toggle',
  template: `
    <label class="switch">
      <input
        class="switch-input"
        type="checkbox"
        [checked]="active"
        (change)="onToggle()" />
      <span
        class="switch-label"
        [attr.data-on]="onText"
        [attr.data-off]="offText"
        [style.background]="active ? onColor : offColor"></span>
      <span class="switch-handle"></span>
    </label>
  `,
  styles: [
    `
      .switch {
        position: relative;
        display: block;
        width: 100px;
        height: 30px;
        padding: 3px;
        margin: 2px;
        background: -webkit-linear-gradient(top, #eeeeee, #ffffff 25px);
        border-radius: 18px;
        box-shadow:
          inset 0 -1px white,
          inset 0 1px 1px rgba(0, 0, 0, 0.05);
        cursor: pointer;
        box-sizing: content-box;
      }
      .switch-input {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        box-sizing: content-box;
      }
      .switch-input:checked ~ .switch-label {
        box-shadow:
          inset 0 1px 2px rgba(0, 0, 0, 0.15),
          inset 0 0 3px rgba(0, 0, 0, 0.2);
      }
      .switch-input:checked ~ .switch-label:before {
        opacity: 0;
      }
      .switch-input:checked ~ .switch-label:after {
        opacity: 1;
      }
      .switch-input:checked ~ .switch-handle {
        left: 74px;
        box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
      }
      .switch-label {
        position: relative;
        display: block;
        height: inherit;
        background: #eceeef;
        font-size: 10px;
        text-transform: uppercase;
        border-radius: inherit;
        box-shadow:
          inset 0 1px 2px rgba(0, 0, 0, 0.12),
          inset 0 0 2px rgba(0, 0, 0, 0.15);
        box-sizing: content-box;
        transition: All 0.3s ease;
        -webkit-transition: All 0.3s ease;
        -moz-transition: All 0.3s ease;
        -o-transition: All 0.3s ease;
      }
      .switch-label:before {
        position: absolute;
        top: 50%;
        margin-top: -0.5em;
        line-height: 1;
        -webkit-transition: inherit;
        -moz-transition: inherit;
        -o-transition: inherit;
        transition: inherit;
        box-sizing: content-box;
        content: attr(data-off);
        right: 11px;
        color: #ffffff;
        text-shadow: 0 1px rgba(0, 0, 0, 0.2);
      }
      .switch-label:after {
        position: absolute;
        top: 50%;
        margin-top: -0.5em;
        line-height: 1;
        -webkit-transition: inherit;
        -moz-transition: inherit;
        -o-transition: inherit;
        transition: inherit;
        box-sizing: content-box;
        content: attr(data-on);
        left: 11px;
        color: #ffffff;
        text-shadow: 0 1px rgba(0, 0, 0, 0.2);
        opacity: 0;
      }
      .switch-handle {
        position: absolute;
        top: 4px;
        left: 4px;
        width: 28px;
        height: 28px;
        background: -webkit-linear-gradient(top, #ffffff 40%, #f0f0f0);
        border-radius: 100%;
        box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
        transition: All 0.3s ease;
        -webkit-transition: All 0.3s ease;
        -moz-transition: All 0.3s ease;
        -o-transition: All 0.3s ease;
      }
      .switch-handle:before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -6px 0 0 -6px;
        width: 12px;
        height: 12px;
        background: -webkit-linear-gradient(top, #eeeeee, #ffffff);
        border-radius: 6px;
        box-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
      }
    `,
  ],
})
export class SlideToggleComponent {
  active = false;

  onText = 'ON';
  onColor = 'var(--ab-color-success)';

  offText = 'OFF';
  offColor = 'var(--ab-color-info)';

  constructor(@Inject(ADAPTABLE_API) private adaptableApi: AdaptableApi) {}

  onToggle() {
    this.active = !this.active;
    this.onChange(this.active);
  }

  onChange(toggleValue: boolean) {
    // overwritten in onSetup()
  }
}
```

**`src/app/quick-search.component.ts`**

```ts
import {
  ADAPTABLE_API,
  AdaptableApi,
} from '@adaptabletools/adaptable-angular-aggrid';
import {Component, Inject} from '@angular/core';

@Component({
  standalone: false,
  selector: 'quick-search',
  template: `
    <div class="quickSearchComponent">
      <input
        type="text"
        class="ab-Input ab-Input--type-text"
        [disabled]="isDisabled"
        (input)="onSearchChange($event)" />
      <button
        type="button"
        class="ab-SimpleButton ab-SimpleButton--font-weight=normal ab-SimpleButton--variant-raised"
        [class.ab-SimpleButton--tone-info]="!isDisabled"
        [disabled]="isDisabled"
        (click)="resetQuickSearch()">
        Clear
      </button>
    </div>
  `,
  styles: [
    `
      .ab-Input.ab-Input--type-text {
        border: var(--ab-cmp-input__border);
      }
      .quickSearchComponent {
        display: flex;
        align-items: center;
        gap: calc(var(--ab-base-space) * 2);
      }
    `,
  ],
})
export class QuickSearchComponent {
  isDisabled = false;

  constructor(@Inject(ADAPTABLE_API) private adaptableApi: AdaptableApi) {
    // disable Quick Search when in Pivot mode
    const isCurrentLayoutInPivotMode = () =>
      this.adaptableApi.layoutApi.isCurrentLayoutPivot();
    this.isDisabled = isCurrentLayoutInPivotMode();

    this.adaptableApi.eventApi.on('LayoutChanged', () => {
      this.isDisabled = isCurrentLayoutInPivotMode();
      if (this.isDisabled) {
        // just to avoid yet another dependency on @angular/forms
        (document.querySelector('input.ab-Input') as HTMLInputElement).value =
          '';
      }
    });
  }

  onSearchChange(event: any) {
    const searchTerm = event.target?.value || '';
    this.adaptableApi.quickSearchApi.runQuickSearch(searchTerm);
  }

  resetQuickSearch() {
    this.adaptableApi.quickSearchApi.clearQuickSearch();
  }
}
```

**`src/app/app.module.ts`**

```ts
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AgGridModule} from 'ag-grid-angular';
import {AdaptableAngularAgGridModule} from '@adaptabletools/adaptable-angular-aggrid';
import {AppComponent} from './app.component';
import {SlideToggleComponent} from './slide-toggle.component';
import {QuickSearchComponent} from './quick-search.component';

@NgModule({
  declarations: [AppComponent, SlideToggleComponent, QuickSearchComponent],
  imports: [BrowserModule, AgGridModule, AdaptableAngularAgGridModule],
  providers: [],
  bootstrap: [AppComponent],
  // @ts-ignore FIXME #AFL required only for Codesandbox (which uses an old rendering engine), since Ivy (Angular >9) 'entryComponents' is no longer required in standalone apps
  entryComponents: [SlideToggleComponent, QuickSearchComponent],
})
export class AppModule {}
```

<!-- /framework -->

<!-- framework: react -->
### React

When using AdapTable React, bespoke toolbar content is provided via the `frameworkComponent` property in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

- This is only required if you wish to provide **bespoke content** in the Custom Toolbar
- See above on how to display Buttons or an inline Form

### Providing Bespoke Toolbar Content

This is a standard React Component of type `ReactFrameworkComponent`.

It can be as complicated and configurable as required.

Developers will typically provide a reference to the [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) for use when controls in the Panel are accessed.

```tsx
export const SlideToggle = (props: SlideToggleProps) => {
  const {
    defaultValue = false,
    onText = 'ON',
    onColor = 'var(--ab-color-success)',
    offText = 'OFF',
    offColor = 'var(--ab-color-info)',
    onToggleChange,
  } = props;

  const [toggleValue, setToggleValue] = useState(defaultValue);

  return (
    <>
      <label className="switch">
        <input
          className="switch-input"
          type="checkbox"
          checked={toggleValue}
          onChange={() => {
            const newValue = !toggleValue;
            setToggleValue(newValue);
            onToggleChange(newValue);
          }}
        />
        <span
          className="switch-label"
          data-on={onText}
          data-off={offText}
          style={{background: toggleValue ? onColor : offColor}}></span>
        <span className="switch-handle"></span>
      </label>
    </>
  );
};
```

Reference the Component created in Step 1 to the `customToolbars` collection in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

This has 3 properties:

- `frameworkComponent` - the Component to be added
- `name` - how it is referenced in AdapTable
- `title` - what is shown in the Toolbar

```tsx {3}
const adaptableOptions: AdaptableOptions = {
  dashboardOptions: {
    customToolbars: [
      {
        name: 'LayoutToggle',
        title: 'Current layout',
        frameworkComponent: ({adaptableApi}) => {
          return (
            <SlideToggle
              onText={'Pivot'}
              offText={'Standard'}
              onToggleChange={(toggleValue: boolean) => {
                if (toggleValue) {
                  adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
                } else {
                  adaptableApi.layoutApi.setLayout('Standard Layout');
                }
              }}
            />
          );
        },
      },
    ],
  },
};
```

**Example: React Components as Custom Toolbars**

Providing React Components as Custom Toolbars

- Three Custom Toolbars: layout toggle, custom quick search, and GitHub Stars gradient toggle

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

```text
src/
  agGridModules.ts       [template]
  App.tsx
  columnDefs.ts          [template]
  CustomQuickSearch.tsx
  gridOptions.ts         [template]
  index.tsx              [template]
  onAdaptableReady.ts    [template]
  rowData.ts             [template]
  SlideToggle.tsx
  styles.css             [template + shown below]
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#react).

**`src/App.tsx`**

```ts
import * as React from 'react';
import {useState} from 'react';
import {
  Adaptable,
  AdaptableApi,
  AdaptableOptions,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable-react-aggrid';

import {GridOptions} from 'ag-grid-enterprise';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {SlideToggle} from './SlideToggle';
import {CustomQuickSearch} from './CustomQuickSearch';
import {WebFramework} from './rowData';

const App: React.FunctionComponent = () => {
  const adaptableApiRef = React.useRef<AdaptableApi>(null);

  const [adaptOptions, setAdaptOptions] = useState<
    AdaptableOptions<WebFramework>
  >({
    primaryKey: 'id',
    adaptableId: 'Custom Toolbar Demo',
    stateOptions: {loadState: () => Promise.resolve({})},
    dashboardOptions: {
      customToolbars: [
        {
          name: 'LayoutToggle',
          title: 'Current layout',
          frameworkComponent: ({adaptableApi}) => {
            return (
              <SlideToggle
                onText={'Pivot'}
                offText={'Standard'}
                onToggleChange={(toggleValue: boolean) => {
                  if (toggleValue) {
                    adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
                  } else {
                    adaptableApi.layoutApi.setLayout('Standard Layout');
                  }
                }}
              />
            );
          },
        },
        {
          name: 'StyledColumnToggle',
          title: 'GitHub Stars Gradient',
          frameworkComponent: ({adaptableApi}) => {
            return (
              <SlideToggle
                defaultValue={true}
                onColor={'#a52a2a'}
                offColor={'var(--ab-color-primary-foreground)'}
                onToggleChange={(toggleValue: boolean) => {
                  const styledColumn =
                    adaptableApi.styledColumnApi.getStyledColumnForColumnId(
                      'github_stars'
                    );
                  if (toggleValue) {
                    adaptableApi.styledColumnApi.unSuspendStyledColumn(
                      styledColumn
                    );
                  } else {
                    adaptableApi.styledColumnApi.suspendStyledColumn(
                      styledColumn
                    );
                  }
                }}
              />
            );
          },
        },
        {
          name: 'CustomQuickSearch',
          title: 'Quick Search',
          frameworkComponent: ({adaptableApi}) => {
            return <CustomQuickSearch adaptableApi={adaptableApi} />;
          },
        },
      ],
    },
    initialState: {
      Dashboard: {
        Tabs: [
          {
            Name: 'Grid Configuration',
            Toolbars: [
              'LayoutToggle',
              'Layout',
              'CustomQuickSearch',
              'StyledColumnToggle',
            ],
          },
        ],
      },
      Theme: {CurrentTheme: 'dark'},
      Layout: {
        CurrentLayout: 'Standard Layout',
        Layouts: [
          {
            Name: 'Standard Layout',
            TableColumns: [
              'name',
              'language',
              'github_stars',
              'topics',
              'license',
              'created_at',
              'has_wiki',
              'updated_at',
              'pushed_at',
              'github_watchers',
              'description',
              'open_issues_count',
              'closed_issues_count',
              'open_pr_count',
              'closed_pr_count',
              'has_projects',
              'has_pages',
              'week_issue_change',
            ],
            AutoSizeColumns: true,
          },
          {
            Name: 'Pivot Cols Layout',
            PivotColumns: ['license'],
            PivotGroupedColumns: ['language'],
            PivotAggregationColumns: [
              {
                ColumnId: 'github_watchers',
                AggFunc: 'sum',
              },
              {
                ColumnId: 'github_stars',
                AggFunc: 'sum',
              },
            ],
          },
        ],
      },
      StyledColumn: {
        StyledColumns: [
          {
            ColumnId: 'github_stars',
            Name: 'github_stars Gradient',
            GradientStyle: {
              RangeValueType: 'Number',
              CellRanges: [{Min: 'Col-Min', Max: 'Col-Max', Color: '#a52a2a'}],
            },
          },
        ],
      },
      QuickSearch: {
        CellMatchStyle: {
          BackColor: '#a1c0d4',
        },
      },
    },
  });
  const [agGridOptions, setAgGridOptions] = useState<GridOptions>(gridOptions);

  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <div id="demoOutputAbove"></div>
      <Adaptable.Provider
        gridOptions={agGridOptions}
        adaptableOptions={adaptOptions}
        modules={[...agGridModules]}
        onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
          // save a reference to adaptable api
          adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
          onAdaptableReady(adaptableReadyInfo);
        }}>
        <Adaptable.UI style={{flex: 'none'}} />
        <Adaptable.AgGridReact />
      </Adaptable.Provider>
      <div id="demoOutputBelow"></div>
    </div>
  );
};
export default App;
```

**`src/SlideToggle.tsx`**

```ts
import * as React from 'react';
import {useState} from 'react';

export interface SlideToggleProps {
  defaultValue?: boolean;
  onText?: string;
  onColor?: string;
  offText?: string;
  offColor?: string;
  onToggleChange(toggleValue: boolean): void;
}
export const SlideToggle = (props: SlideToggleProps) => {
  const {
    defaultValue = false,
    onText = 'ON',
    onColor = 'var(--ab-color-success)',
    offText = 'OFF',
    offColor = 'var(--ab-color-info)',
    onToggleChange,
  } = props;

  const [toggleValue, setToggleValue] = useState(defaultValue);

  return (
    <>
      <label className="switch">
        <input
          className="switch-input"
          type="checkbox"
          checked={toggleValue}
          onChange={() => {
            const newValue = !toggleValue;
            setToggleValue(newValue);
            onToggleChange(newValue);
          }}
        />
        <span
          className="switch-label"
          data-on={onText}
          data-off={offText}
          style={{background: toggleValue ? onColor : offColor}}></span>
        <span className="switch-handle"></span>
      </label>
    </>
  );
};
```

**`src/CustomQuickSearch.tsx`**

```ts
import * as React from 'react';
import {useEffect, useState} from 'react';
import {AdaptableApi} from '@adaptabletools/adaptable-react-aggrid';

export const CustomQuickSearch = ({
  adaptableApi,
}: {
  adaptableApi: AdaptableApi;
}) => {
  const [searchTerm, setSearchTerm] = useState('');

  const isCurrentLayoutInPivotMode = () =>
    adaptableApi.layoutApi.isCurrentLayoutPivot();
  const [isDisabled, setIsDisabled] = useState(isCurrentLayoutInPivotMode());
  useEffect(() => {
    const unsubscribeListener = adaptableApi.eventApi.on(
      'LayoutChanged',
      () => {
        const isPivotLayout = isCurrentLayoutInPivotMode();
        setIsDisabled(isPivotLayout);
        if (isPivotLayout) {
          setSearchTerm('');
        }
      }
    );
    return () => {
      unsubscribeListener?.();
    };
  }, []);

  useEffect(() => {
    adaptableApi.quickSearchApi.runQuickSearch(searchTerm);
  }, [searchTerm]);

  const onSearchChange = (event: any) => {
    const searchText = event.target?.value || '';
    setSearchTerm(searchText);
  };

  return (
    <div className="customQuickSearch">
      <input
        type="text"
        className="ab-Input ab-Input--type-text"
        value={searchTerm}
        disabled={isDisabled}
        onChange={onSearchChange}
      />
      <button
        type="button"
        className={`ab-SimpleButton ab-SimpleButton--font-weight=normal ab-SimpleButton--variant-raised ${
          !isDisabled ? 'ab-SimpleButton--tone-info' : ''
        }`}
        disabled={isDisabled}
        onClick={() => setSearchTerm('')}>
        Clear
      </button>
    </div>
  );
};
```

**`src/styles.css`**

```css
/*
  toggle-switch
*/
.switch {
  position: relative;
  display: block;
  width: 100px;
  height: 30px;
  padding: 3px;
  margin: 2px;
  background: -webkit-linear-gradient(top, #eeeeee, #ffffff 25px);
  border-radius: 18px;
  box-shadow: inset 0 -1px white, inset 0 1px 1px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  box-sizing: content-box;
}
.switch-input {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  box-sizing: content-box;
}
.switch-input:checked ~ .switch-label {
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15),
    inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.switch-input:checked ~ .switch-label:before {
  opacity: 0;
}
.switch-input:checked ~ .switch-label:after {
  opacity: 1;
}
.switch-input:checked ~ .switch-handle {
  left: 74px;
  box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
}
.switch-label {
  position: relative;
  display: block;
  height: inherit;
  background: #eceeef;
  font-size: 10px;
  text-transform: uppercase;
  border-radius: inherit;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12),
    inset 0 0 2px rgba(0, 0, 0, 0.15);
  box-sizing: content-box;
  transition: All 0.3s ease;
  -webkit-transition: All 0.3s ease;
  -moz-transition: All 0.3s ease;
  -o-transition: All 0.3s ease;
}
.switch-label:before {
  position: absolute;
  top: 50%;
  margin-top: -0.5em;
  line-height: 1;
  -webkit-transition: inherit;
  -moz-transition: inherit;
  -o-transition: inherit;
  transition: inherit;
  box-sizing: content-box;
  content: attr(data-off);
  right: 11px;
  color: #ffffff;
  text-shadow: 0 1px rgba(0, 0, 0, 0.2);
}
.switch-label:after {
  position: absolute;
  top: 50%;
  margin-top: -0.5em;
  line-height: 1;
  -webkit-transition: inherit;
  -moz-transition: inherit;
  -o-transition: inherit;
  transition: inherit;
  box-sizing: content-box;
  content: attr(data-on);
  left: 11px;
  color: #ffffff;
  text-shadow: 0 1px rgba(0, 0, 0, 0.2);
  opacity: 0;
}
.switch-handle {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 28px;
  height: 28px;
  background: -webkit-linear-gradient(top, #ffffff 40%, #f0f0f0);
  border-radius: 100%;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
  transition: All 0.3s ease;
  -webkit-transition: All 0.3s ease;
  -moz-transition: All 0.3s ease;
  -o-transition: All 0.3s ease;
}
.switch-handle:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -6px 0 0 -6px;
  width: 12px;
  height: 12px;
  background: -webkit-linear-gradient(top, #eeeeee, #ffffff);
  border-radius: 6px;
  box-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
}

/*
 Custom quick search
*/
.customQuickSearch {
  display: flex;
  align-items: center;
  gap: calc(var(--ab-base-space) * 2);
}
.customQuickSearch .ab-Input.ab-Input--type-text {
  border: var(--ab-cmp-input__border);
}
```



<!-- /framework -->

<!-- framework: vue -->
### Vue

When using AdapTable Vue, bespoke toolbar content is provided via the `frameworkComponent` property in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

- This is only required if you wish to provide **bespoke Vue component(s)** in the Custom Toolbar
- See above on how to display Buttons or an inline Form

### Providing Bespoke Toolbar Content

This is a standard Vue Component of type `VueFrameworkComponent`.

It can be as complicated and configurable as required.

Developers will typically provide a reference to the [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) for use when controls in the Panel are accessed.

```js
const props = defineProps({
  adaptableApi: {
    type: Object,
    required: true,
  },
});

<template>
  <label class="switch">
    <input
      class="switch-input"
      type="checkbox"
      :checked="toggleValue"
      @change="handleChange" />
    <span
      class="switch-label"
      :data-on="props.onText"
      :data-off="props.offText"
      :style="{
        background: toggleValue ? props.onColor : props.offColor,
      }"></span>
    <span class="switch-handle"></span>
  </label>
</template>
```

Reference the Component created in Step 1 to the `customToolbars` collection in [Dashboard Options](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md).

This has 3 properties:

- `name` - how it is referenced in AdapTable
- `title` - what is shown in the Toolbar
- `frameworkComponent` - the Component to be added

```tsx {3}
const adaptableOptions: AdaptableOptions = {
  dashboardOptions: {
    customToolbars: [
      {
        name: 'LayoutToggle',
        title: 'Current layout',
        frameworkComponent: ({adaptableApi}) => {
          return h(SlideToggle, {
            offText: 'Standard',
            offColor: 'var(--ab-color-primary-foreground)',
            onToggleChange: (toggleValue: boolean) => {
              if (toggleValue) {
                adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
              } else {
                adaptableApi.layoutApi.setLayout('Standard Layout');
              }
            },
          });
        },
      },
    ],
  },
}}
```

**Example: Vue Components as Custom Toolbars**

Providing Vue Components as Custom Toolbars

- Three Custom Toolbars: layout toggle, custom quick search, and GitHub Stars gradient toggle

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

```text
public/
  index.html             [template]
src/
  agGridModules.ts       [template]
  App.vue
  columnDefs.ts          [template]
  CustomQuickSearch.vue
  gridOptions.ts         [template]
  main.ts                [template]
  onAdaptableReady.ts    [template]
  rowData.ts             [template]
  shims-vue.d.ts         [template]
  SlideToggle.vue
  styles.css             [template]
.babelrc                 [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#vue).

**`src/App.vue`**

```ts
<script setup lang="ts">
import {h} from 'vue';
import {
  AdaptableProvider,
  AdaptableAgGridVue,
  AdaptableUI,
  AdaptableOptions,
} from '@adaptabletools/adaptable-vue3-aggrid';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {WebFramework} from './rowData';
import CustomQuickSearch from './CustomQuickSearch.vue';
import SlideToggle from './SlideToggle.vue';

const adaptableOpts: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Toolbar Demo',
  stateOptions: {loadState: () => Promise.resolve({})},
  dashboardOptions: {
    customToolbars: [
      {
        name: 'LayoutToggle',
        title: 'Current layout',
        frameworkComponent: ({adaptableApi}) => {
          return h(SlideToggle, {
            offText: 'Standard',
            offColor: 'var(--ab-color-primary-foreground)',
            onToggleChange: (toggleValue: boolean) => {
              if (toggleValue) {
                adaptableApi.layoutApi.setLayout('Pivot Cols Layout');
              } else {
                adaptableApi.layoutApi.setLayout('Standard Layout');
              }
            },
          });
        },
      },
      {
        name: 'StyledColumnToggle',
        title: 'GitHub Stars Gradient',
        frameworkComponent: ({adaptableApi}) => {
          return h(SlideToggle, {
            defaultValue: true,
            onColor: '#a52a2a',
            offColor: 'var(--ab-color-primary-foreground)',
            onToggleChange: toggleValue => {
              const styledColumn =
                adaptableApi.styledColumnApi.getStyledColumnForColumnId(
                  'github_stars'
                );
              if (toggleValue) {
                adaptableApi.styledColumnApi.unSuspendStyledColumn(
                  styledColumn
                );
              } else {
                adaptableApi.styledColumnApi.suspendStyledColumn(styledColumn);
              }
            },
          });
        },
      },
      {
        name: 'CustomQuickSearch',
        title: 'Quick Search',
        frameworkComponent: ({adaptableApi}) =>
          h(CustomQuickSearch, {adaptableApi}),
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Grid Configuration',
          Toolbars: [
            'LayoutToggle',
            'Layout',
            'CustomQuickSearch',
            'StyledColumnToggle',
          ],
        },
      ],
    },
    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',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
        },
        {
          Name: 'Pivot Cols Layout',
          PivotColumns: ['license'],
          PivotGroupedColumns: ['language'],
          PivotAggregationColumns: [
            {
              ColumnId: 'github_watchers',
              AggFunc: 'sum',
            },
            {
              ColumnId: 'github_stars',
              AggFunc: 'sum',
            },
          ],
        },
      ],
    },
    StyledColumn: {
      StyledColumns: [
        {
          ColumnId: 'github_stars',
          Name: 'github_stars Gradient',
          GradientStyle: {
            RangeValueType: 'Number',
            CellRanges: [{Min: 'Col-Min', Max: 'Col-Max', Color: '#a52a2a'}],
          },
        },
      ],
    },
    QuickSearch: {
      Style: {
        BackColor: '#a1c0d4',
      },
    },
  },
};
</script>

<template>
  <AdaptableProvider
    :gridOptions="gridOptions"
    :adaptableOptions="adaptableOpts"
    :modules="agGridModules"
    @onAdaptableReady="onAdaptableReady">
    <div style="display: flex; flex-direction: column; height: 100vh">
      <AdaptableUI />
      <AdaptableAgGridVue style="flex: 1" />
    </div>
  </AdaptableProvider>
</template>
```

**`src/SlideToggle.vue`**

```ts
<script setup lang="ts">
import {ref} from 'vue';

const props = defineProps({
  defaultValue: {
    type: Boolean,
    default: false,
  },
  onText: {
    type: String,
    default: 'ON',
  },
  onColor: {
    type: String,
    default: 'var(--ab-color-success)',
  },
  offText: {
    type: String,
    default: 'OFF',
  },
  offColor: {
    type: String,
    default: 'var(--ab-color-info)',
  },
});

const emit = defineEmits<{
  (e: 'toggleChange', value: boolean): boolean;
}>();

const toggleValue = ref(props.defaultValue);

function handleChange() {
  toggleValue.value = !toggleValue.value;
  emit('toggleChange', toggleValue.value);
}
</script>

<template>
  <label class="switch">
    <input
      class="switch-input"
      type="checkbox"
      :checked="toggleValue"
      @change="handleChange" />
    <span
      class="switch-label"
      :data-on="props.onText"
      :data-off="props.offText"
      :style="{
        background: toggleValue ? props.onColor : props.offColor,
      }"></span>
    <span class="switch-handle"></span>
  </label>
</template>

<style scoped>
.switch {
  position: relative;
  display: block;
  width: 100px;
  height: 30px;
  padding: 3px;
  margin: 2px;
  background: linear-gradient(to bottom, #eeeeee, #ffffff 25px);
  border-radius: 18px;
  box-shadow:
    inset 0 -1px white,
    inset 0 1px 1px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  box-sizing: content-box;
}
.switch-input {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  box-sizing: content-box;
}
.switch-input:checked ~ .switch-label {
  box-shadow:
    inset 0 1px 2px rgba(0, 0, 0, 0.15),
    inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.switch-input:checked ~ .switch-label:before {
  opacity: 0;
}
.switch-input:checked ~ .switch-label:after {
  opacity: 1;
}
.switch-input:checked ~ .switch-handle {
  left: 74px;
  box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
}
.switch-label {
  position: relative;
  display: block;
  height: inherit;
  background: #eceeef;
  font-size: 10px;
  text-transform: uppercase;
  border-radius: inherit;
  box-shadow:
    inset 0 1px 2px rgba(0, 0, 0, 0.12),
    inset 0 0 2px rgba(0, 0, 0, 0.15);
  box-sizing: content-box;
  transition: All 0.3s ease;
  -webkit-transition: All 0.3s ease;
  -moz-transition: All 0.3s ease;
  -o-transition: All 0.3s ease;
}
.switch-label:before {
  position: absolute;
  top: 50%;
  margin-top: -0.5em;
  line-height: 1;
  -webkit-transition: inherit;
  -moz-transition: inherit;
  -o-transition: inherit;
  transition: inherit;
  box-sizing: content-box;
  content: attr(data-off);
  right: 11px;
  color: #ffffff;
  text-shadow: 0 1px rgba(0, 0, 0, 0.2);
}
.switch-label:after {
  position: absolute;
  top: 50%;
  margin-top: -0.5em;
  line-height: 1;
  -webkit-transition: inherit;
  -moz-transition: inherit;
  -o-transition: inherit;
  transition: inherit;
  box-sizing: content-box;
  content: attr(data-on);
  left: 11px;
  color: #ffffff;
  text-shadow: 0 1px rgba(0, 0, 0, 0.2);
  opacity: 0;
}
.switch-handle {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 28px;
  height: 28px;
  background: linear-gradient(to bottom, #ffffff 40%, #f0f0f0);
  border-radius: 100%;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
  transition: All 0.3s ease;
  -webkit-transition: All 0.3s ease;
  -moz-transition: All 0.3s ease;
  -o-transition: All 0.3s ease;
}
.switch-handle:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -6px 0 0 -6px;
  width: 12px;
  height: 12px;
  background: linear-gradient(to bottom, #eeeeee, #ffffff);
  border-radius: 6px;
  box-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
}
</style>
```

**`src/CustomQuickSearch.vue`**

```ts
<script setup lang="ts">
import {ref, onMounted, onUnmounted, watch, PropType} from 'vue';

const props = defineProps({
  adaptableApi: {
    type: Object,
    required: true,
  },
});

const searchTerm = ref('');
const isDisabled = ref(isCurrentLayoutInPivotMode());

function isCurrentLayoutInPivotMode() {
  return !!props.adaptableApi.layoutApi.isCurrentLayoutPivot();
}

function onSearchChange(event) {
  searchTerm.value = event.target.value || '';
}

function clearSearch() {
  searchTerm.value = '';
}

onMounted(() => {
  const unsubscribeListener = props.adaptableApi.eventApi.on(
    'LayoutChanged',
    () => {
      const isPivotLayout = isCurrentLayoutInPivotMode();
      isDisabled.value = isPivotLayout;
      if (isPivotLayout) {
        searchTerm.value = '';
      }
    }
  );

  onUnmounted(() => {
    unsubscribeListener?.();
  });
});

watch(searchTerm, newSearchTerm => {
  props.adaptableApi.quickSearchApi.runQuickSearch(newSearchTerm);
});
</script>

<template>
  <div class="customQuickSearch">
    <input
      type="text"
      class="ab-Input ab-Input--type-text"
      v-model="searchTerm"
      :disabled="isDisabled"
      @input="onSearchChange" />
    <button
      type="button"
      :class="[
        'ab-SimpleButton ab-SimpleButton--font-weight=normal ab-SimpleButton--variant-raised',
        !isDisabled ? 'ab-SimpleButton--tone-info' : '',
      ]"
      :disabled="isDisabled"
      @click="clearSearch">
      Clear
    </button>
  </div>
</template>

<style scoped>
.customQuickSearch {
  display: flex;
  align-items: center;
  gap: calc(var(--ab-base-space) * 2);
}
.customQuickSearch .ab-Input.ab-Input--type-text {
  border: var(--ab-cmp-input__border);
}
</style>
```



<!-- /framework -->

## Configuring Custom Toolbars

A Custom Toolbar can be configured to display up to 2 Buttons via the `toolbarActions` property of the [`CustomToolbar`](https://www.adaptabletools.com/docs/reference/customtoolbar.md) object (by default neither will display):

- `Close` - closes the Custom Toolbar
- `Configure` - enables the Custom Toolbar to be configured

If a Custom Toolbar is closed, you need to open the Dashboard page in the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md) to put it back in a Tab

- When the `Configure` action is clicked it triggers the [Custom Toolbar Configured Event](https://www.adaptabletools.com/docs/technical-reference-dashboard/index.md)
- This allows custom functionality to be performed
