---
product: "AG Studio"
title: "Custom Widgets"
description: "Custom widgets add application-defined widgets to AG Studio, for cases the provided widgets do not cover."
framework: javascript
version: "3.1.0"
related:
    - title: "Widgets Overview"
      url: "https://www.ag-grid.com/studio/archive/3.1.0/javascript/widget-overview/"
    - title: "Configuring Widgets"
      url: "https://www.ag-grid.com/studio/archive/3.1.0/javascript/widget-configuration/"
    - title: "Form Configuration"
      url: "https://www.ag-grid.com/studio/archive/3.1.0/javascript/custom-widgets-form/"
llms: "https://www.ag-grid.com/studio/archive/3.1.0/llms.txt"
---

# Custom Widgets

Custom widgets add application-defined widgets to AG Studio, for cases the provided widgets do not cover.

#### Custom Widget

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  AgWidgetFormParams,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { CustomDef, MyRegistry } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const initialState: AgReportState<MyRegistry> = {
  pages: [
    {
      id: "page1",
      widgets: {
        "1": {
          type: "customWidget",
          dataMapping: {
            value: [
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
      },
      widgetLayout: {
        "1": {
          xTrack: 0,
          yTrack: 0,
          xSpan: 24,
          ySpan: 12,
        },
      },
      selection: {
        type: "widget",
        id: "1",
      },
    },
  ],
  selectedPageId: "page1",
  panels: {
    filters: {
      collapsed: true,
    },
    data: {
      collapsed: true,
    },
  },
};

const widgets = createWidgets<MyRegistry>({
  additionalTypes: [
    {
      id: "customWidget",
      icon: {
        url: "https://www.ag-grid.com/studio/images/brandmark.svg",
      },
      label: "Custom Widget",
      dataMapping: {
        value: {
          type: "field",
          supportedRoles: ["numeric"],
          requires: { cardinality: "one" },
          required: true,
        },
      },
      form: (params: AgWidgetFormParams<CustomDef>) => {
        const defaultForm = params.createDefaults({
          dataMappingItems: [
            {
              key: "value",
              label: "Value",
            },
          ],
        });
        defaultForm.items[1].items.push({
          type: "number",
          id: "format.style.valueFontSize",
          label: "Value Font Size",
          defaultValue: 48,
        });
        return defaultForm;
      },
      comp: CustomWidget,
      defaultSize: {
        width: 400,
        height: 300,
      },
      minSize: {
        width: 200,
        height: 100,
      },
      ai: {
        description:
          "Custom widget used for displaying values in an interesting way.",
      },
    },
  ],
  menu: [
    {
      label: "Custom",
      widgetIds: ["customWidget"],
    },
  ],
});

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "edit",
  initialState,
  widgets,
};

let studioApi: AgStudioApi<MyRegistry>;

// setup Studio after the page has finished loading
const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);

fetch("https://www.ag-grid.com/studio/archive/3.1.0/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data) =>
    studioApi!.setProperty("data", { sources: [{ id: "medals", data }] }),
  );
```

[Live example: Custom Widget](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/custom-widget/typescript/)

The example above demonstrates a custom widget showing a single data value.

## Creating a Custom Widget

To provide a custom widget, implement the `AgTypeScriptWidgetDefinition` interface.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `comp` | `string \| (() => AgTypeScriptComponent<AgWidgetParams<TOut, any, any>>)` |  | Custom component. Either: A `string` that matches a custom component in the studio `components` property A custom TypeScript component class |
| `id` | `TWidgetType` |  | Unique widget identifier (e.g., 'grid', 'value', 'column-chart-grouped'). |
| `label` | `string` |  | Display label, or localisation key. |
| `icon` | `AgCustomIcon` |  | Optional icon for widget display. One of: `string` - an SVG string `{ className: string }` - A CSS class name `{ url: string }` - A URL to an SVG A `string` icon is parsed as HTML, so supply it only from trusted sources. |
| `dataMapping` | `AgDataMappingDefinitions<keyof TOut["dataMapping"] & string>` |  | Optional data mappings for the widget (if required). This defines the type of fields and how they are used by the widget. |
| `formatShape` | `Function` |  | Optional format shape. The shape created by this function will be used for parsing the `format` configuration. If provided, `format` state will be passed through the `parse()` method before being loaded into Studio. If using AI, the shape is required, as it uses the schema. |
| `form` | `Function` |  | Form configuration using typed form builder. |
| `defaultState` | `Partial<TOut>` |  | Optional default state. If provided, this will override the default values in the form. It also allows defaults to be set for the data mapping and sort. |
| `extends` | `"value" \| "multi-kpi" \| "grid" \| "pivot-grid" \| "column-chart-grouped" \| "column-chart-stacked" \| "column-chart-stacked-100" \| "bar-chart-grouped" \| "bar-chart-stacked" \| "bar-chart-stacked-100" \| "line-chart" \| "area-chart" \| "area-chart-stacked" \| "area-chart-stacked-100" \| "scatter-chart" \| "bubble-chart" \| "radar-line-chart" \| "radar-area-chart" \| "radial-column-chart" \| "nightingale-chart" \| "radial-bar-chart" \| "pie-chart" \| "donut-chart" \| "funnel-chart" \| "cone-funnel-chart" \| "pyramid-chart" \| "treemap-chart" \| "sunburst-chart" \| "histogram-chart" \| "box-plot-chart" \| "range-column-chart" \| "range-bar-chart" \| "range-area-chart" \| "radial-gauge" \| "linear-gauge" \| "button-filter" \| "list-filter" \| "date-filter" \| "text" \| "image" \| "combo-chart-grouped-column-line" \| "combo-chart-stacked-column-line"` |  | Optional default widget ID that this definition extends. Use this if overriding or pre-configuring one of the default widgets. This ensure that any values that no longer appear in the form are still correctly mapped / set to the right default value. For custom widgets, this should not be set. |
| `defaultSize` | `AgWidgetSize` |  | Default widget size when created. |
| `minSize` | `AgWidgetSize` |  | Minimum widget size constraints. |
| `toolbar` | `(AgWidgetToolbarButton \| AgDefaultWidgetAction)[]` | `['duplicate', 'delete']` | Optional toolbar configuration. Can be a built-in item (`'delete'` or `'duplicate'`) or a custom item. If the item provides an action, that will be performed, otherwise it will be dispatched as a `'toolbarAction'` event to the widget. If providing a custom value, `'duplicate'` and `'delete'` must be provided if required. |
| `featureConfig` | `AgWidgetFeatureConfig` |  | Optional feature configuration. |
| `options` | `TOptions` |  | Optional options passed directly to widget. |
| `ai` | `AgWidgetAiMetadata` |  | Optional structured AI metadata for this widget type. |

> **Note**
>
> A string `icon` is parsed as HTML, so supply it only from a trusted source. Use a CSS class name or an SVG URL for icons that come from anywhere else.

Custom widgets are provided to the `widgets` property, similar to the [Available Widgets](https://www.ag-grid.com/studio/archive/3.1.0/javascript/widget-configuration/#available-widgets) configuration.

Provide the custom widget definitions to the `createWidgets(params)` helper function, and add them to the menu.

```js
const studioProperties = {
    widgets: (widgetConfig) => createWidgets<CustomRegistry>({
        additionalTypes: [customWidgetDefinition],
        menu: [
            ...widgetConfig.menu,
            {
                label: 'Custom',
                widgetIds: ['customWidget'],
            },
        ]
    }),

    // other studio properties ...
}
```

For the types to work correctly, the custom widgets should be defined in the [Registry Type](https://www.ag-grid.com/studio/archive/3.1.0/javascript/registry-type/).

```ts
interface CustomRegistry extends AgBaseRegistry {
    widgets: readonly (AgDefaultWidgetDefinition | CustomWidgetDefinition)[]
}
```

### Form

The widget `form` configures the form displayed in the edit panel. The values from the form are passed in the widget params.

See the [Form Configuration](https://www.ag-grid.com/studio/archive/3.1.0/javascript/custom-widgets-form/) page for more details.

### AI Integration

For a custom widget to work with [AI](https://www.ag-grid.com/studio/archive/3.1.0/javascript/ai/), the `formatShape` and `ai` properties must be defined in the widget definition.

The shape returned by `formatShape` is used to provide the AI with the schema for the `format` property of the widget, and to validate the `format` value the AI sets via state.

## Data Mapping

The `dataMapping` property defines the fields or fieldsets that are required to configure the widget, and the required relationships between them.

For example, to configure a line chart, the data mapping might look like this:

```ts
const dataMapping = {
    xAxisKey: {
        type: 'field', // Only a single field allowed
        // All types of value allowed
        supportedRoles: ['category', 'numeric', 'temporal'],
        requires: { cardinality: 'many' }, // Many values are accepted
        required: true, // Required field - widget cannot be displayed without it
        sort: true, // Show the sort menu
        aiDescription: 'Field for the x axis.', // Description when used with AI
    },
    yAxisKey: {
        type: 'fieldset', // Multiple fields allowed
        supportedRoles: ['numeric'], // Only numeric values allowed
        // For each `xAxisKey`, this must map to a single value
        requires: { per: 'dataMapping.xAxisKey', cardinality: 'one' },
        required: true, // Required field - widget cannot be displayed without it
        sort: true, // Show the sort menu
        // Description when used with AI
        aiDescription: 'Field(s) for the y axis. Each field becomes a separate series.',
    },
};
```

A widget does not have to rely on a data mapping to choose its fields. See [Reading the Report Schema](https://www.ag-grid.com/studio/archive/3.1.0/javascript/custom-widgets/#reading-the-report-schema).

## Widget Component

The custom component is a class that implements the `AgTypeScriptComponent` interface.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `getGui` | `Function` |  | Return the DOM element of your component, this is what Studio puts into the DOM |
| `destroy` | `Function` |  | Gets called once by Studio when the component is being removed; if your component needs to do any cleanup, do it here |
| `init` | `Function` |  | Called once on init. |
| `refresh` | `Function` |  | Called for every subsequent params update. A widget's `refresh` is also called when the data it loaded with `getData` changes, with the same params object as before, so load the data again on every call rather than only when the params change. |

The `init` and `refresh` methods receive params of type `AgWidgetParams`.

### Custom Widget Params

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `widgetId` | `string` |  | Widget ID. |
| `widgetType` | `string` |  | Widget type. |
| `format` | `TWidget["format"]` |  | Widget format as constructed from the widget form. |
| `dataMapping` | `AgWidgetDataMapping<TWidget>` |  | Widget data mapping values. |
| `sort` | `AgWidgetSort[] \| undefined` |  | Widget sort if defined. |
| `api` | `AgCoreStudioApi` |  | Studio API. |
| `context` | `TContext` |  | Application context as set on `context` Studio property. |
| `config` | `AgWidgetConfig<TWidget, TOptions>` |  | Widget configuration. |
| `widgetApi` | `AgWidgetApi` |  | Widget API. Provides access to retrieve data. |

### Display State

Widgets have four different display states that can be set via `widgetApi.setDisplayState(state, metadata?)`. These will trigger different overlays to be displayed by the layout on top of the widget. The states are:

- `displayed` - The widget has data and is ready to display. Studio will show no overlay; the widget is rendered normally.
- `loading` - The widget is loading. Metadata defaults to `{ prominent: true }` for a solid loading overlay; use `{ prominent: false }` for an unobtrusive refresh indicator that keeps the previous content visible.
- `noData` - The widget has no data (e.g. everything is filtered out or the data is empty). Studio will show an overlay with "No data to display".
- `incompleteDataMapping` - The widget does not have all of the required fields set. Studio will show an overlay with the field selection inputs.

Each time the widget updates, set the relevant status as needed.

```ts
widgetApi.setDisplayState('loading');
const response = await widgetApi.getData(request);
// ... process the response
widgetApi.setDisplayState('displayed');
```

### Loading Data

Data is loaded via `widgetApi.getData(request)`. The request can be constructed from the data mapping values in the params.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `kind` | `"flat"` |  | Flat row query. Omit for backwards compatibility. |
| `fields` | `AgWidgetField[]` |  | List of fields to return in the query. Unaggregated fields will automatically be used for grouping. |
| `sort` | `AgSort[]` |  | Sort the result based on the provided fields. |
| `filter` | `AgFilter[]` |  | Additional filter to apply. Page-level filters and widget-level filters (including from filter widgets and cross filters) will be automatically applied. |
| `limit` | `AgLimit` |  | Limit the number of rows returned, or for pagination. |

A widget can make several data requests at once. Each call resolves with the data for its own request.

To make a call replace an earlier one, give both calls the same query ID in the options argument, for example `getData(request, { queryId: 'rows' })`. When the request changes, Studio stops running the earlier request. If the earlier call is still waiting, it resolves with no data and with `replaced` set on its response. Do not show that response as the result of the request, because the later call gets the data.

```ts
const response = await widgetApi.getData(request, { queryId: 'rows' });
if (response.replaced) return;
```

Give each request its own query ID, or none. Two different requests with one query ID replace each other even when the widget makes them together, for example in one `Promise.all` or in two React components that render together. After a call to `enableStudioDevValidations()`, Studio warns of this in the browser console. With a production build of React, it warns only of requests made together in one block of code, such as one `Promise.all`.

### Keeping Data Up to Date

When the report's data changes, for example through a [Transaction](https://www.ag-grid.com/studio/archive/3.1.0/javascript/live-data/), Studio keeps a widget up to date in one of three ways:

- A widget that loads its data with `getData` is refreshed, and asks for all its data again.
- A widget that passes `onDataUpdated` to `getData` receives each newer response there, and is not refreshed for it.
- A widget that keeps a set of queries across changes it makes itself uses a data handle, which delivers each query's response again whenever it changes.

#### Refreshed Through getData

A widget that loads its data with `getData` needs no extra code. When the data its queries read changes, Studio calls the widget's `refresh` again, and the `getData` calls it makes return the newer data.

- **At most once a second.** When the data changes faster than that, the next refresh shows the latest data, and the states in between are never shown.
- **Never a mix.** Studio refreshes only once the newer data of every query the widget made reflects the same change, so one refresh never shows one query's data from before a change beside another's from after it.
- **Hidden tabs wait.** Refreshes are drawn with the page, so a widget in a hidden tab is refreshed once the tab is shown again, with the latest data.

#### Updated Through onDataUpdated

Pass `onDataUpdated` in the options of `getData` to receive each newer response for the query without a refresh. The call resolves with the first response. Each newer response, after a change to the data the query reads or to a filter or cross filter that applies to it, goes to `onDataUpdated`.

```ts
const response = await widgetApi.getData(query, {
    onDataUpdated: (newer) => draw(newer),
});
draw(response);
```

- **Once per frame, together.** Newer responses are passed on just before the page is drawn, and only once every query of the widget has a response and any two queries that read the same table read the same changes to it. In a hidden tab they wait until the tab is shown.
- **Give every query `onDataUpdated`** when the widget shows the queries' responses together. A query asked for without it catches up only when the widget is next refreshed.
- **Kept while the widget asks for it.** A refresh, such as for a change to the widget's params, asks for the widget's queries again. A later call with the same `queryId`, or with no `queryId` and an equal query, replaces the earlier call and its `onDataUpdated`. When the query is equal, it resolves at once with the latest response, unless a change is still updating the widget's queries. A query the widget does not ask for again during a refresh is no longer kept up to date once that refresh has finished.

A data engine that does not keep queries up to date as its data changes never calls `onDataUpdated`.

#### Data Handles

A data handle keeps a set of queries up to date and passes each query's response to a listener whenever the data it reads, a filter or cross filter that affects it, or its definition changes. Call `getDataHandle` on the widget API, open the handle with a listener, then set the queries by key. Each takes the same query and options as `getData`.

```ts
const handle = widgetApi.getDataHandle();
handle.open(({ results }) => {
    for (const { key, response } of results) {
        // ... apply the response for the query `key`
    }
});
handle.set('rows', { query: rowsQuery });
handle.set('totals', { query: totalsQuery });
```

Set a key again to change its query, and remove it to stop keeping it up to date. The handle is closed when the widget is destroyed.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `batchByFrame` | `boolean` |  | Deliver once per animation frame, with every response that arrived since the last delivery, the latest for each query, just before the page is drawn. When data changes faster than the page is drawn, this skips the work of applying responses that would never be seen. Browsers pause animation frames in a hidden tab, so deliveries then wait until the tab is shown again. On by default. Skipping never reorders: a response is skipped only when a newer one for the same query has replaced it, so each query's responses arrive in the order its data changed, never an older one after a newer. The same holds without batching. How responses for different queries line up is set by `consistent`. `false` delivers each response as soon as it arrives, with any others that arrived at the same moment, whether the tab is shown or not. Use it for a listener that does not draw, such as one that raises alerts or passes the data on, or for a widget that waits for an animation frame of its own before drawing, which batching would delay by a frame. |
| `consistent` | `boolean` |  | Deliver only responses that agree with each other: after every delivery, each table that two or more queries read is at one position across the responses last delivered for them. A response that would break this waits until the other queries' responses have caught up with the same change to the data, and is then delivered with them. So a widget never shows one query's result from before a change beside another's from after it. A query that has not delivered since it was set, or since its definition last changed, does not hold the others back. Queries that a filter, cross filter or field change, or a reload of the data, runs again are delivered together once each has answered, so none is shown beside another's response from before that change. Queries that read no table in common always agree. The order of a delivery's `results` does not say which is newer; compare their `position` for that. Defaults to `batchByFrame`: on when batching by frame, off when delivering straight away. Off, each query delivers on its own, and one delivery can hold responses that read the same table at different positions. Turn it off for a widget whose queries feed separate parts that need not agree, so that a slow query does not hold back a fast one. |

#### What a Data Handle Guarantees

- **Complete responses.** Each response is the whole result for its query, as `getData` would return it, never a partial change. When the widget highlights its cross filter, `response.results` and `response.crossFilter` always reflect the same data.
- **In order for each query.** A query's responses arrive in the order its data changed, never an older one after a newer. A response may be skipped, but only when a newer one for the same query has replaced it before delivery.
- **Consistent across queries.** By default, a delivery never leaves the widget showing one query's result from before a change beside another's from after it: a newer response waits until the others have caught up, and they are delivered together. A query that has not delivered since it was set, or since its query last changed, does not hold the others back. Turn this off with `consistent: false` for queries that feed separate parts of the widget and need not agree, so that a slow query does not hold back a fast one.
- **Once per frame.** By default, responses are delivered just before the page is drawn, the latest for each query, so a widget does no work for data that would never be seen. In a hidden tab, deliveries wait until the tab is shown. With `batchByFrame: false`, each response is delivered as soon as it arrives, whether the tab is shown or not.
- **Comparable positions.** Each response carries a `position`, saying how far it reflects each table it read. Two responses that read a table at the same position saw the same data in it. The order of a delivery's `results` does not say which is newer.
- **Failures still deliver.** A query that does not complete delivers a result holding no rows, with `metadata.error` set where the result carries metadata, so the widget can show the failure.

A data engine that does not keep queries up to date as its data changes still delivers again after filter, cross filter and definition changes, and when the data is reloaded, but not on changes to the data. Its responses carry no `position`, so queries are never held back for one another.

#### Across Widgets

Each widget is kept up to date on its own, so while the data is changing two widgets can briefly show it at different points. Once the data stops changing, every widget comes to show the same, latest data: a widget with a data handle at the next frame after its queries have run again, and a widget refreshed through `getData` within about a second.

### Reading the Report Schema

A widget does not have to rely on a data mapping to choose its fields. Call `getSchema()` on the widget API to list every table and field in the report's schema. Tables, and the fields within each table, come back in the order the data panel lists them.

The example below defines a widget with no data mapping. It reads the schema, then shows a grid with one column per field.

#### Schema Widget

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { MyRegistry } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const initialState: AgReportState<MyRegistry> = {
  pages: [
    {
      id: "page1",
      widgets: {
        "1": {
          type: "schemaWidget",
          dataMapping: {},
        },
      },
      widgetLayout: {
        "1": {
          xTrack: 0,
          yTrack: 0,
          xSpan: 24,
          ySpan: 24,
        },
      },
      selection: {
        type: "widget",
        id: "1",
      },
    },
  ],
  selectedPageId: "page1",
  panels: {
    filters: {
      collapsed: true,
    },
    data: {
      collapsed: true,
    },
  },
};

const widgets = createWidgets<MyRegistry>({
  additionalTypes: [
    {
      id: "schemaWidget",
      icon: {
        url: "https://www.ag-grid.com/studio/images/brandmark.svg",
      },
      label: "Schema Widget",
      form: (params) =>
        params.createDefaults({
          dataMappingItems: [],
        }),
      comp: CustomWidget,
      defaultSize: {
        width: 800,
        height: 400,
      },
      minSize: {
        width: 400,
        height: 200,
      },
      ai: {
        description:
          "Shows every field in the report schema, with data for each one, in a grid.",
      },
    },
  ],
  menu: [
    {
      label: "Custom",
      widgetIds: ["schemaWidget"],
    },
  ],
});

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "edit",
  initialState,
  widgets,
};

let studioApi: AgStudioApi<MyRegistry>;

// setup Studio after the page has finished loading
const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);

fetch("https://www.ag-grid.com/studio/archive/3.1.0/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data) =>
    studioApi!.setProperty("data", { sources: [{ id: "medals", data }] }),
  );
```

[Live example: Schema Widget](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/schema-widget/typescript/)

### Popups

If a custom widget creates its own popup that is anchored outside of the custom widget DOM element (e.g. like a third-party date picker), then the popup element needs to have the 'ag-custom-component-popup' CSS class. This allows Studio to determine correctly when focus is within a widget.

## Cross-Filtering

#### Custom Widget with Cross Filter

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  AgWidgetFormParams,
  AgWidgetsConfig,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { CustomDef, MyRegistry } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const initialState: AgReportState<MyRegistry> = {
  pages: [
    {
      id: "page1",
      widgets: {
        "1": {
          type: "customWidget",
          dataMapping: {
            category: [
              {
                id: "medals.country",
              },
            ],
            value: [
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
        "2": {
          type: "grid",
          dataMapping: {
            cols: [
              {
                id: "medals.country",
              },
              {
                id: "medals.athlete",
              },
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
        "3": {
          type: "column-chart-grouped",
          dataMapping: {
            categoryKey: [
              {
                id: "medals.year",
              },
            ],
            valueKey: [
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
      },
      widgetLayout: {
        "1": {
          xTrack: 0,
          yTrack: 0,
          xSpan: 12,
          ySpan: 36,
        },
        "2": {
          xTrack: 12,
          yTrack: 18,
          xSpan: 12,
          ySpan: 18,
        },
        "3": {
          xTrack: 12,
          yTrack: 0,
          xSpan: 12,
          ySpan: 18,
        },
      },
    },
  ],
  selectedPageId: "page1",
  panels: {
    filters: {
      collapsed: true,
    },
  },
};

const widgets = (widgetConfig: AgWidgetsConfig<MyRegistry>) =>
  createWidgets<MyRegistry>({
    additionalTypes: [
      {
        id: "customWidget",
        icon: {
          url: "https://www.ag-grid.com/studio/images/brandmark.svg",
        },
        label: "Custom Widget",
        dataMapping: {
          category: {
            type: "field",
            supportedRoles: ["category"],
            requires: { cardinality: "many" },
            required: true,
          },
          value: {
            type: "field",
            supportedRoles: ["numeric"],
            requires: { per: "dataMapping.category", cardinality: "one" },
            required: true,
          },
        },
        form: (params: AgWidgetFormParams<CustomDef>) => {
          return params.createDefaults({
            dataMappingItems: [
              {
                key: "category",
                label: "Category",
              },
              {
                key: "value",
                label: "Value",
              },
            ],
            supportsCrossHighlight: true,
          });
        },
        comp: CustomWidget,
        defaultSize: {
          width: 400,
          height: 300,
        },
        minSize: {
          width: 200,
          height: 100,
        },
        featureConfig: {
          crossFilter: {
            supportsHighlight: true,
          },
        },
      },
    ],
    menu: [
      {
        label: "Custom",
        widgetIds: ["customWidget"],
      },
      ...widgetConfig.menu,
    ],
  });

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "view",
  initialState,
  widgets,
};

let studioApi: AgStudioApi<MyRegistry>;

// setup Studio after the page has finished loading
const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);

fetch("https://www.ag-grid.com/studio/archive/3.1.0/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data) =>
    studioApi!.setProperty("data", { sources: [{ id: "medals", data }] }),
  );
```

[Live example: Custom Widget with Cross Filter](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/cross-filter-widget/typescript/)

To implement cross-filtering from within a custom widget, the cross filter methods can be used from the widget API.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `toggleCrossFilter` | `Function` |  | Set a cross filter. Does nothing while the widget's `format.triggerCrossFilter` is `false`. |
| `resetCrossFilter` | `Function` |  | Clear cross filter. |
| `getCrossFilterSelections` | `Function` |  | Get the current cross filter for this widget. A widget that calls this is refreshed whenever the cross filter changes, even when its `format.crossFilter` is `'none'`, so it can show a selection that another widget cleared. |

Every selection belongs to a `group`, a zero-based number identifying which of the widget's selections is being set. A widget holds one selection per group, and selections in different groups are independent of each other. A widget that holds a single selection should pass `group: 0`; a widget that selects on several fields at once should give each field its own group.

A widget that selects on several fields *together* - a sankey link or a matrix cell, where one click means "this channel **and** this product" - should use a multi value selection instead of a group per field. Each `toggleCrossFilter` call with `type: 'multiValue'` contributes one combination of field and value pairs; the pairs within a combination must all match, and a row is included when it matches any one of the combinations the selection holds. Toggling the same set of pairs again removes that combination.

```ts
api.toggleCrossFilter({
    type: 'multiValue',
    values: [
        { field: channelField, value: 'Online' },
        { field: productField, value: 'Clothing' },
    ],
    group: 0,
});
```

To support the cross filter highlight behaviour (similar to some of the default charts, e.g. column charts), enable it in the widget definition.

```ts
 const widgetDefinition = {
    // ...
    featureConfig: {
        crossFilter: {
            supportsHighlight: true
        }
    }
 };
```

When this is enabled, the data response will contain two datasets. The original data (`response.results`), and the cross-filtered data (`response.crossFilter`).

To let report users stop the widget starting cross filters, pass `true` as the second argument of `createCrossFilterSection(supportsCrossHighlight, supportsTriggerCrossFilter)`. This adds a **Click to Cross Filter** checkbox to the widget's Cross-Filtering section in the Edit Panel. The value is stored as `format.triggerCrossFilter` (a boolean, treated as `true` when unset), and the widget must declare `triggerCrossFilter` in its `formatShape`, otherwise the checkbox value is not kept when the report is reloaded. While it is `false`, `widgetApi.toggleCrossFilter` does nothing.

## Context Menu

Right-clicking a custom widget calls the `getContextMenuItems` studio property, like a right-click anywhere else in the dashboard. A custom widget can also pass details of what was right-clicked, such as the row's values, to the callback. Right-click a row in the custom widget below to see it.

#### Custom Widget with Context Menu

```ts
import {
  AgContextMenuItem,
  AgGetContextMenuParams,
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  AgWidgetFormParams,
  AgWidgetsConfig,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { CustomDef, MyRegistry } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const initialState: AgReportState<MyRegistry> = {
  pages: [
    {
      id: "page1",
      widgets: {
        "1": {
          type: "customWidget",
          dataMapping: {
            category: [
              {
                id: "medals.country",
              },
            ],
            value: [
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
        "2": {
          type: "grid",
          dataMapping: {
            cols: [
              {
                id: "medals.country",
              },
              {
                id: "medals.athlete",
              },
              {
                id: "medals.gold",
                aggregation: "sum",
              },
            ],
          },
        },
      },
      widgetLayout: {
        "1": {
          xTrack: 0,
          yTrack: 0,
          xSpan: 12,
          ySpan: 36,
        },
        "2": {
          xTrack: 12,
          yTrack: 0,
          xSpan: 12,
          ySpan: 36,
        },
      },
    },
  ],
  selectedPageId: "page1",
  panels: {
    filters: {
      collapsed: true,
    },
  },
};

const widgets = (widgetConfig: AgWidgetsConfig<MyRegistry>) =>
  createWidgets<MyRegistry>({
    additionalTypes: [
      {
        id: "customWidget",
        icon: {
          url: "https://www.ag-grid.com/studio/images/brandmark.svg",
        },
        label: "Custom Widget",
        dataMapping: {
          category: {
            type: "field",
            supportedRoles: ["category"],
            requires: { cardinality: "many" },
            required: true,
          },
          value: {
            type: "field",
            supportedRoles: ["numeric"],
            requires: { per: "dataMapping.category", cardinality: "one" },
            required: true,
          },
        },
        form: (params: AgWidgetFormParams<CustomDef>) => {
          return params.createDefaults({
            dataMappingItems: [
              {
                key: "category",
                label: "Category",
              },
              {
                key: "value",
                label: "Value",
              },
            ],
          });
        },
        comp: CustomWidget,
        defaultSize: {
          width: 400,
          height: 300,
        },
        minSize: {
          width: 200,
          height: 100,
        },
      },
    ],
    menu: [
      {
        label: "Custom",
        widgetIds: ["customWidget"],
      },
      ...widgetConfig.menu,
    ],
  });

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "edit",
  initialState,
  widgets,
  getContextMenuItems,
};

let studioApi: AgStudioApi<MyRegistry>;

function getContextMenuItems(
  params: AgGetContextMenuParams,
): AgContextMenuItem[] {
  const { widgetType, widgetContext } = params;
  if (widgetType !== "customWidget" || widgetContext == null) {
    return [];
  }
  const { category, value } = widgetContext;
  return [
    {
      name: `Show details for ${category}`,
      action: () => console.log(`${category}: ${value}`),
    },
    "separator",
    {
      name: `Copy "${value}"`,
      action: () => navigator.clipboard.writeText(value),
    },
  ];
}

// setup Studio after the page has finished loading
const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);

fetch("https://www.ag-grid.com/studio/archive/3.1.0/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data) =>
    studioApi!.setProperty("data", { sources: [{ id: "medals", data }] }),
  );
```

[Live example: Custom Widget with Context Menu](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/context-menu-widget/typescript/)

To pass these details, listen for the `contextmenu` event on an element in the widget and pass the event to `showContextMenu` on the widget API, along with a `context` and `filter`. If the callback returns items, the menu opens at the location of the event. Opening or closing it does not select the widget or change its state.

```ts
row.addEventListener('contextmenu', (event) => {
    widgetApi.showContextMenu({
        event,
        context: { category, value },
        filter: { field: categoryField, operator: 'equals', value: category },
        restoreFocusOnClose: () => row.focus(),
    });
});
```

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `showContextMenu` | `Function` |  | Open the Studio context menu at the location of the event. The menu items come from the `getContextMenuItems` studio property. When that property is not set, nothing is shown and the browser's own context menu is left to open. When it is set but returns no items, nothing is shown and, for a mouse event, the browser's own context menu is suppressed. A right-click made with the Ctrl key (Cmd on macOS) held opens nothing and leaves the browser's own context menu to open, unless the `allowContextMenuWithControlKey` studio property is `true`. |

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `event` | `MouseEvent \| Touch` |  | The mouse or touch event that opened the menu. The menu is shown at the event's location. |
| `context` | `TWidgetContext` |  | Describes what the menu was opened on. Passed unchanged to the `getContextMenuItems` studio property as `widgetContext`. |
| `filter` | `AgFilter` |  | A filter matching the item the menu was opened on. Passed to `getContextMenuItems` as a filter definition. |
| `restoreFocusOnClose` | `Function` |  | Returns focus to the widget. Called when the menu closes after keyboard use, and passed to `getContextMenuItems` so that a menu action which opens its own popup can return focus later. |

Studio provides no menu items of its own. The application supplies them with the `getContextMenuItems` studio property, which is called once for each right-click. A menu opens only when it returns items. A right-click on the widget outside an element that calls `showContextMenu` has no `widgetContext`, so check for it before reading its values.

```ts
const studioProperties = {
    // ...
    getContextMenuItems: ({ widgetType, widgetContext }) => {
        if (widgetType !== 'customWidget' || widgetContext == null) {
            return [];
        }
        return [
            {
                name: `Show details for ${widgetContext.category}`,
                action: () => showDetails(widgetContext),
            },
        ];
    },
};
```

If `getContextMenuItems` is not set, or returns an empty array, no menu is shown. When `getContextMenuItems` is set, the browser's own context menu is suppressed, so the widget does not need to call `preventDefault` on the event. When it is not set, the browser's context menu opens as normal. A right-click with `⌃ Ctrl`/`⌘ Cmd` held also leaves the browser's context menu to open, unless the `allowContextMenuWithControlKey` studio property is `true`. See [Context Menu - Showing the Browser Context Menu](https://www.ag-grid.com/studio/archive/3.1.0/javascript/context-menu/#showing-the-browser-context-menu).

The `filter` is passed to `getContextMenuItems` as a filter definition. It can be used to show the data behind the item that was right-clicked, as described in [Drill Through](https://www.ag-grid.com/studio/archive/3.1.0/javascript/drill-through/).

## AG Grid & AG Charts in Widgets

As well as the built-in AG Grid and AG Charts widgets, it is possible to create your own custom widgets using AG Grid and AG Charts.

To match the AG Grid theming in Studio, use `studioGridTheme` and pass it to the `theme` grid option.

For AG Charts, set the following in chart options (where `api` is the Studio API in the widget params):

```ts
const chartOptions = {
    // ... other options
    theme: getChartTheme(api),
    background: {
        fill: 'transparent'
    }
};
```

> **Note**
>
> Using AG Grid Enterprise or AG Charts Enterprise in a custom widget requires the relevant AG Grid Enterprise or AG Charts Enterprise licence.

> **Note**
>
> The AG Grid and AG Charts themes contain the theme variables used by grid and chart widgets within Studio. Theme variables not used within Studio may not have values set. If using other AG Grid/AG Charts features, you may need to set additional theme variables.

## Custom Widget Examples

### Sankey Chart

A Sankey diagram visualises flow between two sets of nodes, sized by a numeric measure. This example maps a sales dataset (channel → product category) alongside a bar chart of the same revenue measure.

#### Custom Widget: Sankey

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  AgWidgetFormParams,
  AgWidgetsConfig,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { SOURCE_ID, ordersData } from "./data.ts";
import { MyRegistry, SankeyDef } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const widgets = (widgetConfig: AgWidgetsConfig<MyRegistry>) =>
  createWidgets<MyRegistry>({
    additionalTypes: [
      {
        id: "sankey-widget",
        label: "Sankey",
        icon: { url: "https://www.ag-grid.com/studio/images/brandmark.svg" },
        dataMapping: {
          from: {
            type: "field",
            supportedRoles: ["category"],
            requires: { cardinality: "many" },
            required: true,
            aiDescription: "Source nodes of the flow.",
          },
          to: {
            type: "field",
            supportedRoles: ["category"],
            requires: { cardinality: "many" },
            required: true,
            aiDescription: "Target nodes of the flow.",
          },
          value: {
            type: "field",
            supportedRoles: ["numeric"],
            requires: { cardinality: "one" },
            required: true,
            aiDescription: "Numeric measure that sizes each flow.",
          },
        },
        form: (params: AgWidgetFormParams<SankeyDef>) =>
          params.createDefaults({
            dataMappingItems: [
              { key: "from", label: "From" },
              { key: "to", label: "To" },
              { key: "value", label: "Value" },
            ],
          }),
        comp: CustomWidget,
        defaultSize: { width: 600, height: 400 },
        minSize: { width: 300, height: 200 },
      },
    ],
    menu: [
      { label: "Custom", widgetIds: ["sankey-widget"] },
      ...widgetConfig.menu,
    ],
  });

const initialState: AgReportState<MyRegistry> = {
  panels: {
    filters: { collapsed: true },
    edit: { collapsed: true },
    data: { collapsed: true },
  },
  pages: [
    {
      id: "page-1",
      widgets: {
        sankey: {
          type: "sankey-widget",
          dataMapping: {
            from: [{ id: `${SOURCE_ID}.channel` }],
            to: [{ id: `${SOURCE_ID}.product` }],
            value: [{ id: `${SOURCE_ID}.revenue`, aggregation: "sum" }],
          },
        },
        "revenue-by-channel": {
          type: "bar-chart-grouped",
          dataMapping: {
            categoryKey: [{ id: `${SOURCE_ID}.channel` }],
            valueKey: [{ id: `${SOURCE_ID}.revenue`, aggregation: "sum" }],
          },
          format: {
            title: { enabled: true, text: "Revenue by Channel" },
          },
        },
      },
      widgetLayout: {
        sankey: { xTrack: 0, yTrack: 0, xSpan: 16, ySpan: 29 },
        "revenue-by-channel": { xTrack: 16, yTrack: 0, xSpan: 8, ySpan: 29 },
      },
    },
  ],
  selectedPageId: "page-1",
};

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "view",
  initialState,
  widgets,
  data: ordersData,
};

let studioApi: AgStudioApi<MyRegistry>;

const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);
```

[Live example: Custom Widget: Sankey](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/sankey-widget/typescript/)

The widget takes no part in cross filtering: it requests its data with `crossFilter: 'none'`, so the flow diagram always covers the whole dataset and its node set never reflows. For a custom widget that does cross filter, see the Custom Widget with Cross Filter example above.

### Choropleth Map

A choropleth map shades geographic regions by a numeric measure. This example renders UK county boundaries using AG Charts' `map-shape` series and supports click-to-cross-filter alongside a regional bar chart.

#### Custom Widget: Choropleth Map

```ts
import {
  AgReportState,
  AgStudioApi,
  AgStudioProperties,
  AgWidgetFormParams,
  AgWidgetsConfig,
  createStudio,
  createWidgets,
  enableStudioDevValidations,
} from "ag-studio";
import { CustomWidget } from "./customWidget.ts";
import { SOURCE_ID, storeData } from "./data.ts";
import { MapDef, MyRegistry } from "./interfaces.ts";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const widgets = (widgetConfig: AgWidgetsConfig<MyRegistry>) =>
  createWidgets<MyRegistry>({
    additionalTypes: [
      {
        id: "map-widget",
        label: "Choropleth Map",
        icon: { url: "https://www.ag-grid.com/studio/images/brandmark.svg" },
        dataMapping: {
          county: {
            type: "field",
            supportedRoles: ["category"],
            requires: { cardinality: "many" },
            required: true,
            aiDescription: "Category field whose values match UK county names.",
          },
          value: {
            type: "field",
            supportedRoles: ["numeric"],
            requires: { cardinality: "one" },
            required: true,
            aiDescription:
              "Numeric measure that drives the colour intensity of each county.",
          },
        },
        form: (params: AgWidgetFormParams<MapDef>) =>
          params.createDefaults({
            dataMappingItems: [
              { key: "county", label: "County" },
              { key: "value", label: "Value" },
            ],
          }),
        comp: CustomWidget,
        defaultSize: { width: 500, height: 500 },
        minSize: { width: 280, height: 300 },
      },
    ],
    menu: [
      { label: "Custom", widgetIds: ["map-widget"] },
      ...widgetConfig.menu,
    ],
  });

const initialState: AgReportState<MyRegistry> = {
  panels: {
    filters: { collapsed: true },
    edit: { collapsed: true },
    data: { collapsed: true },
  },
  pages: [
    {
      id: "page-1",
      widgets: {
        map: {
          type: "map-widget",
          dataMapping: {
            county: [{ id: `${SOURCE_ID}.county` }],
            value: [{ id: `${SOURCE_ID}.revenue`, aggregation: "sum" }],
          },
        },
        "revenue-by-region": {
          type: "bar-chart-grouped",
          dataMapping: {
            categoryKey: [{ id: `${SOURCE_ID}.region` }],
            valueKey: [{ id: `${SOURCE_ID}.revenue`, aggregation: "sum" }],
          },
          format: {
            crossFilter: "highlight",
            title: { enabled: true, text: "Revenue by Region" },
          },
        },
      },
      widgetLayout: {
        map: { xTrack: 0, yTrack: 0, xSpan: 14, ySpan: 35 },
        "revenue-by-region": { xTrack: 14, yTrack: 0, xSpan: 10, ySpan: 35 },
      },
    },
  ],
  selectedPageId: "page-1",
};

const studioProperties: AgStudioProperties<MyRegistry> = {
  mode: "view",
  initialState,
  widgets,
  data: storeData,
};

let studioApi: AgStudioApi<MyRegistry>;

const studioDiv = document.querySelector<HTMLElement>("#myStudio")!;
studioApi = createStudio(studioDiv, studioProperties);
```

[Live example: Custom Widget: Choropleth Map](https://www.ag-grid.com/studio/archive/3.1.0/examples/custom-widgets/map-widget/typescript/)

The colour domain is clamped to the p10-p90 range of the dataset, preventing a single high-value region from compressing all other counties into a narrow band near the minimum. When counties are selected, a background layer renders the full distribution at reduced opacity to preserve geographic context.
