Custom widgets add application-defined widgets to AG Studio, for cases the provided widgets do not cover.
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgStudio, AgStudioRef } from "ag-studio-react";
import {
AgCoreDefaultRegistry,
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioApiReadyEvent,
AgStudioMode,
AgStudioProperties,
AgWidgetFormParams,
AgWidgetsConfig,
enableStudioDevValidations,
} from "ag-studio";
import { CustomDef, MyRegistry } from "./interfaces.tsx";
import { createWidgets } from "ag-studio-react";
import CustomWidget from "./customWidget.tsx";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const StudioExample = () => {
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [data, setData] = useState<AgDataSourcesDefinition | AgDataEngine>();
const initialState = useMemo<
AgReportState<MyRegistry> | AgReportHistory<MyRegistry>
>(() => {
return {
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 = useMemo<
| AgWidgetsConfig<MyRegistry>
| ((
widgets: AgWidgetsConfig<AgCoreDefaultRegistry>,
) => AgWidgetsConfig<MyRegistry>)
>(() => {
return 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 onApiReady = useCallback((params: AgStudioApiReadyEvent) => {
fetch("https://www.ag-grid.com/studio/archive/3.1.1/example-assets/olympic-winners.json")
.then((resp) => resp.json())
.then((data: any[]) => setData({ sources: [{ id: "medals", data }] }));
}, []);
return (
<div style={containerStyle}>
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<AgStudio<MyRegistry>
style={studioStyle}
className="my-studio-container"
data={data}
initialState={initialState}
widgets={widgets}
mode={"edit"}
onApiReady={onApiReady}
/>
</div>
</div>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<StudioExample />
</StrictMode>,
);
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 AgWidgetDefinition interface.
Unique widget identifier (e.g., 'grid', 'value', 'column-chart-grouped').
|
Display label, or localisation key.
|
Optional icon for widget display. One of: string - an SVG string { className: string } - A CSS class name { url: string } - A URL to an SVG string icon is parsed as HTML, so supply it only from trusted sources.
|
Optional data mappings for the widget (if required). This defines the type of fields and how they are used by the widget.
|
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 configuration using typed form builder.
|
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.
|
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.
|
Custom component. Either: a string that matches a custom component in the studio components property; a custom React component; or a custom TypeScript component class (no React; working directly with the DOM). |
Default widget size when created.
|
Minimum widget size constraints.
|
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. |
Optional feature configuration.
|
Optional options passed directly to widget.
|
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.
Import createWidgets from ag-studio-react rather than ag-studio, so that the React-specific widget defaults are applied.
const widgets = (widgetConfig) => createWidgets<CustomRegistry>({
additionalTypes: [customWidgetDefinition],
menu: [
...widgetConfig.menu,
{
label: 'Custom',
widgetIds: ['customWidget'],
},
]
});
<AgStudio widgets={widgets} />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 React component that receives props of type AgWidgetParams.
Custom Widget Params Copy Link
Widget ID.
|
Widget type.
|
Widget format as constructed from the widget form.
|
Widget data mapping values.
|
Widget sort if defined.
|
Studio API.
|
Application context as set on context Studio property.
|
Widget configuration.
|
Widget API. Provides access to retrieve data.
|
Display State Copy Link
Three convenience components are exported from ag-studio-react to manage display loading states. These will trigger different overlays to be displayed by the layout on top of the widget.
<AgLoadingOverlay />- The widget is loading. Studio will show a loading spinner over the widget.<AgNoDataOverlay />- 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".<AgIncompleteDataMappingOverlay />- The widget does not have all of the required fields set. Studio will show an overlay with the field selection inputs.
function MyComponent({ widgetApi, dataMapping }) {
const response = use(widgetApi.getData(request));
const data = response.results.rows;
if (data.length === 0) return <AgNoDataOverlay />;
return <div>My Component</div>;
}Alternatively, you can use the imperative API widgetApi.setDisplayState(state, metadata?). The states are:
displayed- Studio will show no overlay; the widget is rendered normally.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.noDataincompleteDataMapping
Each time the widget updates, set the relevant status as needed.
useEffect(() => {
const fn = async () => {
widgetApi.setDisplayState('loading');
const response = await widgetApi.getData(request);
// ... process the response
widgetApi.setDisplayState('displayed');
}
fn();
}); Loading Data Copy Link
Data is loaded via widgetApi.getData(request). The request can be constructed from the data mapping values in the params.
This can be combined with React's use API.
const response = use(widgetApi.getData(request));The loading overlay will automatically be displayed while React waits on these requests to finish.
Flat row query. Omit for backwards compatibility.
|
List of fields to return in the query. Unaggregated fields will automatically be used for grouping.
|
Sort the result based on the provided fields.
|
Additional filter to apply. Page-level filters and widget-level filters (including from filter widgets and cross filters) will be automatically applied.
|
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
getDatais refreshed, and asks for all its data again. - A widget that passes
onDataUpdatedtogetDatareceives 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
onDataUpdatedwhen 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 noqueryIdand an equal query, replaces the earlier call and itsonDataUpdated. 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.
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.
|
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
getDatawould return it, never a partial change. When the widget highlights its cross filter,response.resultsandresponse.crossFilteralways 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: falsefor 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'sresultsdoes not say which is newer. - Failures still deliver. A query that does not complete delivers a result holding no rows, with
metadata.errorset 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.
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgStudio, AgStudioRef } from "ag-studio-react";
import {
AgCoreDefaultRegistry,
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioApiReadyEvent,
AgStudioMode,
AgStudioProperties,
AgWidgetsConfig,
enableStudioDevValidations,
} from "ag-studio";
import { MyRegistry } from "./interfaces.tsx";
import { createWidgets } from "ag-studio-react";
import CustomWidget from "./customWidget.tsx";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const StudioExample = () => {
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [data, setData] = useState<AgDataSourcesDefinition | AgDataEngine>();
const initialState = useMemo<
AgReportState<MyRegistry> | AgReportHistory<MyRegistry>
>(() => {
return {
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 = useMemo<
| AgWidgetsConfig<MyRegistry>
| ((
widgets: AgWidgetsConfig<AgCoreDefaultRegistry>,
) => AgWidgetsConfig<MyRegistry>)
>(() => {
return 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 onApiReady = useCallback((params: AgStudioApiReadyEvent) => {
fetch("https://www.ag-grid.com/studio/archive/3.1.1/example-assets/olympic-winners.json")
.then((resp) => resp.json())
.then((data: any[]) => setData({ sources: [{ id: "medals", data }] }));
}, []);
return (
<div style={containerStyle}>
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<AgStudio<MyRegistry>
style={studioStyle}
className="my-studio-container"
data={data}
initialState={initialState}
widgets={widgets}
mode={"edit"}
onApiReady={onApiReady}
/>
</div>
</div>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<StudioExample />
</StrictMode>,
);
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
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgStudio, AgStudioRef } from "ag-studio-react";
import {
AgCoreDefaultRegistry,
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioApiReadyEvent,
AgStudioMode,
AgStudioProperties,
AgWidgetFormParams,
AgWidgetsConfig,
enableStudioDevValidations,
} from "ag-studio";
import { CustomDef, MyRegistry } from "./interfaces.tsx";
import { createWidgets } from "ag-studio-react";
import CustomWidget from "./customWidget.tsx";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const StudioExample = () => {
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [data, setData] = useState<AgDataSourcesDefinition | AgDataEngine>();
const initialState = useMemo<
AgReportState<MyRegistry> | AgReportHistory<MyRegistry>
>(() => {
return {
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 = useMemo<
| AgWidgetsConfig<MyRegistry>
| ((
widgets: AgWidgetsConfig<AgCoreDefaultRegistry>,
) => AgWidgetsConfig<MyRegistry>)
>(() => {
return (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 onApiReady = useCallback((params: AgStudioApiReadyEvent) => {
fetch("https://www.ag-grid.com/studio/archive/3.1.1/example-assets/olympic-winners.json")
.then((resp) => resp.json())
.then((data: any[]) => setData({ sources: [{ id: "medals", data }] }));
}, []);
return (
<div style={containerStyle}>
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<AgStudio<MyRegistry>
style={studioStyle}
className="my-studio-container"
data={data}
initialState={initialState}
widgets={widgets}
mode={"view"}
onApiReady={onApiReady}
/>
</div>
</div>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<StudioExample />
</StrictMode>,
);
To implement cross-filtering from within a custom widget, the cross filter methods can be used from the widget API.
Set a cross filter. Does nothing while the widget's format.triggerCrossFilter is false.
|
Clear cross filter.
|
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(),
});
});In React, pass the native event (event.nativeEvent), not the React synthetic event.
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.
|
The mouse or touch event that opened the menu. The menu is shown at the event's location.
|
Describes what the menu was opened on. Passed unchanged to the getContextMenuItems studio property as widgetContext.
|
A filter matching the item the menu was opened on. Passed to getContextMenuItems as a filter definition.
|
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.
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgStudio, AgStudioRef } from "ag-studio-react";
import {
AgCoreDefaultRegistry,
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioMode,
AgStudioProperties,
AgWidgetFormParams,
AgWidgetsConfig,
enableStudioDevValidations,
} from "ag-studio";
import { SOURCE_ID, ordersData } from "./data.tsx";
import { MyRegistry, SankeyDef } from "./interfaces.tsx";
import { createWidgets } from "ag-studio-react";
import CustomWidget from "./customWidget.tsx";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const StudioExample = () => {
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [data, setData] = useState<AgDataSource>(ordersData);
const widgets = useMemo<
| AgWidgetsConfig<MyRegistry>
| ((
widgets: AgWidgetsConfig<AgCoreDefaultRegistry>,
) => AgWidgetsConfig<MyRegistry>)
>(() => {
return (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 = useMemo<
AgReportState<MyRegistry> | AgReportHistory<MyRegistry>
>(() => {
return {
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",
};
}, []);
return (
<div style={containerStyle}>
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<AgStudio<MyRegistry>
style={studioStyle}
className="my-studio-container"
data={data}
widgets={widgets}
initialState={initialState}
mode={"view"}
/>
</div>
</div>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<StudioExample />
</StrictMode>,
);
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.
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgStudio, AgStudioRef } from "ag-studio-react";
import {
AgCoreDefaultRegistry,
AgDataEngine,
AgDataSourcesDefinition,
AgReportHistory,
AgReportState,
AgStudioApi,
AgStudioMode,
AgStudioProperties,
AgWidgetFormParams,
AgWidgetsConfig,
enableStudioDevValidations,
} from "ag-studio";
import { SOURCE_ID, storeData } from "./data.tsx";
import { MapDef, MyRegistry } from "./interfaces.tsx";
import { createWidgets } from "ag-studio-react";
import CustomWidget from "./customWidget.tsx";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableStudioDevValidations();
}
const StudioExample = () => {
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [data, setData] = useState<AgDataSource>(storeData);
const widgets = useMemo<
| AgWidgetsConfig<MyRegistry>
| ((
widgets: AgWidgetsConfig<AgCoreDefaultRegistry>,
) => AgWidgetsConfig<MyRegistry>)
>(() => {
return (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 = useMemo<
AgReportState<MyRegistry> | AgReportHistory<MyRegistry>
>(() => {
return {
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",
};
}, []);
return (
<div style={containerStyle}>
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<AgStudio<MyRegistry>
style={studioStyle}
className="my-studio-container"
data={data}
widgets={widgets}
initialState={initialState}
mode={"view"}
/>
</div>
</div>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<StudioExample />
</StrictMode>,
);
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.