We just wrapped up AG Studio Launch Week See what we shipped

JavaScript Embedded AnalyticsCustom Widgets

Version 3.1.1

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

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

Creating a Custom Widget Copy Link

To provide a custom widget, implement the AgTypeScriptWidgetDefinition interface.

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
  • TWidgetType
    Unique widget identifier (e.g., 'grid', 'value', 'column-chart-grouped').
    string
    Display label, or localisation key.
    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.
    dataMappingCopy Link
    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.
    formatShapeCopy Link
    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.
    Function
    Form configuration using typed form builder.
    defaultStateCopy Link
    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.
    extendsCopy Link
    "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.
    defaultSizeCopy Link
    AgWidgetSize
    Default widget size when created.
    minSizeCopy Link
    AgWidgetSize
    Minimum widget size constraints.
    toolbarCopy Link
    (AgWidgetToolbarButton | AgDefaultWidgetAction)[]
    default: ['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.
    featureConfigCopy Link
    AgWidgetFeatureConfig
    Optional feature configuration.
    optionsCopy Link
    TOptions
    Optional options passed directly to widget.
    AgWidgetAiMetadata
    Optional structured AI metadata for this widget type.

    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 configuration.

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

    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.

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

    Form Copy Link

    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 page for more details.

    AI Integration Copy Link

    For a custom widget to work with 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 Copy Link

    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:

    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.

    Widget Component Copy Link

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

    getGuiCopy Link
    Function
    Return the DOM element of your component, this is what Studio puts into the DOM
    destroyCopy Link
    Function
    Gets called once by Studio when the component is being removed; if your component needs to do any cleanup, do it here
    Function
    Called once on init.
    refreshCopy Link
    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 Copy Link

    widgetIdCopy Link
    string
    Widget ID.
    widgetTypeCopy Link
    string
    Widget type.
    formatCopy Link
    TWidget["format"]
    Widget format as constructed from the widget form.
    dataMappingCopy Link
    AgWidgetDataMapping<TWidget>
    Widget data mapping values.
    AgWidgetSort[] | undefined
    Widget sort if defined.
    AgCoreStudioApi
    Studio API.
    contextCopy Link
    TContext
    Application context as set on context Studio property.
    configCopy Link
    AgWidgetConfig<TWidget, TOptions>
    Widget configuration.
    widgetApiCopy Link
    AgWidgetApi
    Widget API. Provides access to retrieve data.

    Display State Copy Link

    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.

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

    Loading Data Copy Link

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

    "flat"
    Flat row query. Omit for backwards compatibility.
    fieldsCopy Link
    AgWidgetField[]
    List of fields to return in the query. Unaggregated fields will automatically be used for grouping.
    AgSort[]
    Sort the result based on the provided fields.
    filterCopy Link
    AgFilter[]
    Additional filter to apply. Page-level filters and widget-level filters (including from filter widgets and cross filters) will be automatically applied.
    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.

    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 Copy Link

    When the report's data changes, for example through a Transaction, 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 Copy Link

    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 Copy Link

    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.

    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 Copy Link

    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.

    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.

    batchByFrameCopy Link
    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.
    consistentCopy Link
    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 Copy Link

    • 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 Copy Link

    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 Copy Link

    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.

    Popups Copy Link

    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 Copy Link

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

    toggleCrossFilterCopy Link
    Function
    Set a cross filter. Does nothing while the widget's format.triggerCrossFilter is false.
    resetCrossFilterCopy Link
    Function
    Clear cross filter.
    getCrossFilterSelectionsCopy Link
    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.

    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.

     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 Copy Link

    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.

    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.

    row.addEventListener('contextmenu', (event) => {
        widgetApi.showContextMenu({
            event,
            context: { category, value },
            filter: { field: categoryField, operator: 'equals', value: category },
            restoreFocusOnClose: () => row.focus(),
        });
    });
    showContextMenuCopy Link
    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.
    MouseEvent | Touch
    The mouse or touch event that opened the menu. The menu is shown at the event's location.
    contextCopy Link
    TWidgetContext
    Describes what the menu was opened on. Passed unchanged to the getContextMenuItems studio property as widgetContext.
    filterCopy Link
    AgFilter
    A filter matching the item the menu was opened on. Passed to getContextMenuItems as a filter definition.
    restoreFocusOnCloseCopy Link
    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.

    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.

    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.

    AG Grid & AG Charts in Widgets Copy Link

    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):

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

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

    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 Copy Link

    Sankey Chart Copy Link

    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.

    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 Copy Link

    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.

    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.