# External Chart Libraries

Canonical page: https://www.adaptabletools.com/docs/handbook-charts-external

- Most charting users access the charts provided by AG Grid
- However AdapTable can work with any charting library

AdapTable integrates closely with AG Grid's charts, and is the most common charting use case.

But AdapTable can be used in conjunction with any charting library.

AdapTable's rich [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) and the many [Adaptable Events](https://www.adaptabletools.com/docs/technical-reference-adaptable-events/index.md) make it easier to synchronise data in the Grid with your preferred Charting library.

## Two Patterns

**Context menu charts (first demo)** — Custom context-menu actions call your charting library directly from the current cell selection. This is useful for ad hoc charts without persisting a definition in Adaptable State.

**Persisted external definitions (second demo)** — Register [External Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) (`onShowChart`, `onHideChart`, `isChartOpened`, and related callbacks), store external chart definitions in State, and open them from Charting UI into `chartContainers` — the same persistence model as AG Grid charts.

Callback signatures and types are documented in [Charts Technical Reference](https://www.adaptabletools.com/docs/technical-reference-charts/index.md)

- We are keen to add additional support for external charting and to meet all use cases
- So please contact us if there is specific functionality that you would like us to make available

**Example: External Charts Library**

Using an external chart library

- This demo shows how to use the [Highcharts](https://www.highcharts.com/) Charting library from AdapTable
- From any valid selection (one string and one numeric column) we are able to use the Context Menu to create 3 different chart types:
  - Pie Chart
  - Line Chart
  - Bar Chart

- Select a range that includes a numeric and a string column (we pre-select a range using the [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md))
- Create a **Highcharts** chart by selecting `Show Charts` from the [Context Menu](https://www.adaptabletools.com/docs/ui-context-menu/index.md) (the first item, and only enabled if there is a valid selection) and choose a Chart type

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  chartingService.ts
  columnDefs.ts        [template]
  gridOptions.ts
  icons.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + highcharts
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  ContextMenuContext,
  CustomContextMenuContext,
  SelectedCellInfo,
  UserContextMenuItem,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {chartIcon, pieIcon, lineChartIcon, barChartIcon} from './icons';
import {charginService} from './chartingService';

/**
 * Selection is valid only when:
 * - two columns are selected
 * - one is numeric and the other text
 */
const isSelectionValidForSimpleCharts = (selection: SelectedCellInfo) => {
  // Two columns need to be selected
  if (selection.columns.length !== 2) {
    return false;
  }
  // At least one is numeric
  const oneColumnIsNumeric =
    selection.columns.filter(column => column.dataType === 'number').length ===
    1;
  if (!oneColumnIsNumeric) {
    return false;
  }
  // At least one text
  const oneColumnIsText =
    selection.columns.filter(column => column.dataType === 'text').length === 1;
  if (!oneColumnIsText) {
    return false;
  }

  return true;
};

const contextMenuOptions: AdaptableOptions['contextMenuOptions'] = {
  customContextMenu: (context: CustomContextMenuContext) => {
    const {defaultAgGridMenuStructure, defaultAdaptableMenuStructure} = context;

    const chartMenuItem: UserContextMenuItem = {
      menuType: 'User',
      label: 'Show Charts',
      icon: {
        element: chartIcon,
      },
      subMenuItems: [
        {
          menuType: 'User',
          label: 'Pie Chart',
          icon: {element: pieIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            charginService.showPieChart(selection);
          },
        },
        {
          menuType: 'User',
          label: 'Line Chart',
          icon: {element: lineChartIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            charginService.showLineChart(selection);
          },
        },
        {
          menuType: 'User',
          label: 'Bar Chart',
          icon: {element: barChartIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            charginService.showBarChart(selection);
          },
        },
      ],
    };

    return [
      chartMenuItem,
      '-',
      ...defaultAgGridMenuStructure,
      '-',
      ...defaultAdaptableMenuStructure,
    ];
  },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Using External Charts',
  contextMenuOptions,
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Charting',
          Toolbars: ['Layout'],
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'github_watchers',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/icons.ts`**

```ts
export const chartIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M3 21V17M9 21V13M15 21V15M21 21V11M8.43934 5.56066C8.71079 5.83211 9.08579 6 9.5 6C9.91421 6 10.2892 5.83211 10.5607 5.56066M8.43934 5.56066C8.16789 5.28921 8 4.91421 8 4.5C8 3.67157 8.67157 3 9.5 3C10.3284 3 11 3.67157 11 4.5C11 4.91421 10.8321 5.28921 10.5607 5.56066M8.43934 5.56066L5.56066 8.43934M5.56066 8.43934C5.28921 8.16789 4.91421 8 4.5 8C3.67157 8 3 8.67157 3 9.5C3 10.3284 3.67157 11 4.5 11C5.32843 11 6 10.3284 6 9.5C6 9.08579 5.83211 8.71079 5.56066 8.43934ZM10.5607 5.56066L13.4393 8.43934M13.4393 8.43934C13.1679 8.71079 13 9.08579 13 9.5C13 10.3284 13.6716 11 14.5 11C15.3284 11 16 10.3284 16 9.5C16 9.08579 15.8321 8.71079 15.5607 8.43934M13.4393 8.43934C13.7108 8.16789 14.0858 8 14.5 8C14.9142 8 15.2892 8.16789 15.5607 8.43934M15.5607 8.43934L18.4393 5.56066M18.4393 5.56066C18.7108 5.83211 19.0858 6 19.5 6C20.3284 6 21 5.32843 21 4.5C21 3.67157 20.3284 3 19.5 3C18.6716 3 18 3.67157 18 4.5C18 4.91421 18.1679 5.28921 18.4393 5.56066Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;

export const pieIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M6.4443 3.6853C6.97115 3.33327 7.52766 3.03383 8.10577 2.7894C9.50868 2.19627 10.2101 1.8997 11.1051 2.49296C12 3.08623 12 4.05748 12 6V8C12 9.88561 12 10.8284 12.5858 11.4142C13.1716 12 14.1144 12 16 12H18C19.9425 12 20.9138 12 21.507 12.8949C22.1003 13.7899 21.8037 14.4913 21.2106 15.8942C20.9662 16.4723 20.6667 17.0288 20.3147 17.5557C19.2159 19.2002 17.6541 20.4819 15.8268 21.2388C13.9996 21.9957 11.9889 22.1937 10.0491 21.8078C8.10929 21.422 6.32746 20.4696 4.92894 19.0711C3.53041 17.6725 2.578 15.8907 2.19215 13.9509C1.8063 12.0111 2.00433 10.0004 2.76121 8.17316C3.51809 6.3459 4.79981 4.78412 6.4443 3.6853Z" fill="#1C274C"/>
  <path fill-rule="evenodd" clip-rule="evenodd" d="M13.7739 2.12812C13.8771 1.72698 14.286 1.48549 14.6871 1.58873C18.4658 2.56129 21.4389 5.53443 22.4115 9.31307C22.5147 9.71421 22.2732 10.1231 21.8721 10.2263C21.4709 10.3296 21.0621 10.0881 20.9588 9.68696C20.1225 6.43757 17.5626 3.87772 14.3132 3.04139C13.9121 2.93814 13.6706 2.52926 13.7739 2.12812Z" fill="#1C274C"/>
</svg>
`;

export const lineChartIcon = `
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M21 21H7.8C6.11984 21 5.27976 21 4.63803 20.673C4.07354 20.3854 3.6146 19.9265 3.32698 19.362C3 18.7202 3 17.8802 3 16.2V3M6 15L10 11L14 15L20 9M20 9V13M20 9H16" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;

export const barChartIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M3.29289 9.29289C3 9.58579 3 10.0572 3 11V17C3 17.9428 3 18.4142 3.29289 18.7071C3.58579 19 4.05719 19 5 19C5.94281 19 6.41421 19 6.70711 18.7071C7 18.4142 7 17.9428 7 17V11C7 10.0572 7 9.58579 6.70711 9.29289C6.41421 9 5.94281 9 5 9C4.05719 9 3.58579 9 3.29289 9.29289Z" fill="#1C274C"/>
  <path opacity="0.4" d="M17.2929 2.29289C17 2.58579 17 3.05719 17 4V17C17 17.9428 17 18.4142 17.2929 18.7071C17.5858 19 18.0572 19 19 19C19.9428 19 20.4142 19 20.7071 18.7071C21 18.4142 21 17.9428 21 17V4C21 3.05719 21 2.58579 20.7071 2.29289C20.4142 2 19.9428 2 19 2C18.0572 2 17.5858 2 17.2929 2.29289Z" fill="#1C274C"/>
  <path opacity="0.7" d="M10 7C10 6.05719 10 5.58579 10.2929 5.29289C10.5858 5 11.0572 5 12 5C12.9428 5 13.4142 5 13.7071 5.29289C14 5.58579 14 6.05719 14 7V17C14 17.9428 14 18.4142 13.7071 18.7071C13.4142 19 12.9428 19 12 19C11.0572 19 10.5858 19 10.2929 18.7071C10 18.4142 10 17.9428 10 17V7Z" fill="#1C274C"/>
  <path d="M3 21.25C2.58579 21.25 2.25 21.5858 2.25 22C2.25 22.4142 2.58579 22.75 3 22.75H21C21.4142 22.75 21.75 22.4142 21.75 22C21.75 21.5858 21.4142 21.25 21 21.25H3Z" fill="#1C274C"/>
</svg>
`;
```

**`src/chartingService.ts`**

```ts
import {SelectedCellInfo} from '@adaptabletools/adaptable';
import * as Highcharts from 'highcharts';

const container = 'demoOutputAbove';

/**
 * It goes over the selected cells and groupes them in two sets:
 * - categories: the values of the string column (if there is one)
 * - value: the numeric values
 */
const getCategoriesAndValuesFromSelection = (selection: SelectedCellInfo) => {
  const [col1, col2] = selection.columns;

  // Select the string column as the category column
  const categoryColumn = col1.dataType === 'text' ? col1 : col2;
  const valueColumn = col1.dataType === 'number' ? col1 : col2;

  // Group the selected cells in sets of  [category-name, value]
  const categoryValueSets: [string | number, number][] = [];
  for (let categoryCell of selection.gridCells) {
    if (categoryCell.column.columnId === categoryColumn.columnId) {
      // find corresponding value
      const valueCell = selection.gridCells.find(localGridCell => {
        return (
          localGridCell.rowNode.id === categoryCell.rowNode.id &&
          // and not the same column
          localGridCell.column.columnId !== categoryCell.column.columnId
        );
      });
      if (valueCell) {
        categoryValueSets.push([categoryCell.rawValue, valueCell.rawValue]);
      }
    }
  }
  const categories = categoryValueSets.map(([category]) => category);
  const values = categoryValueSets.map(([category, value]) => value);
  return {categories, values, categoryColumn, valueColumn, categoryValueSets};
};

export const charginService = {
  showLineChart: (selection: SelectedCellInfo) => {
    const {categories, values, categoryColumn, valueColumn} =
      getCategoriesAndValuesFromSelection(selection);

    // @ts-ignore
    Highcharts.chart(container, {
      title: {
        text: 'Dynamic Simple Line Chart',
        align: 'left',
      },
      yAxis: {
        title: {
          text: categoryColumn?.friendlyName,
        },
      },
      xAxis: {
        categories,
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false,
          },
        },
      },
      series: [
        {
          name: `${categoryColumn?.friendlyName} and ${valueColumn?.friendlyName}`,
          data: values,
        },
      ],
      responsive: {
        rules: [
          {
            condition: {
              maxWidth: 500,
            },
            chartOptions: {
              legend: {
                layout: 'horizontal',
                align: 'center',
                verticalAlign: 'bottom',
              },
            },
          },
        ],
      },
    });
  },
  showPieChart: (selection: SelectedCellInfo) => {
    const {categoryColumn, categoryValueSets} =
      getCategoriesAndValuesFromSelection(selection);

    const series = categoryValueSets.map(([category, value]) => ({
      name: category,
      y: value,
    }));

    // @ts-ignore
    Highcharts.chart(container, {
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
      },
      title: {
        text: 'Dynamic Simple Pie Chart',
        align: 'left',
      },
      tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
      },
      accessibility: {
        point: {
          valueSuffix: '%',
        },
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
          },
        },
      },
      series: [
        {
          name: categoryColumn.friendlyName,
          colorByPoint: true,
          data: series,
        },
      ],
    });
  },
  showBarChart: (selection: SelectedCellInfo) => {
    const {categoryColumn, valueColumn, categoryValueSets} =
      getCategoriesAndValuesFromSelection(selection);

    const series: any = [
      {
        name: categoryColumn.friendlyName,
        data: categoryValueSets,
      },
    ];

    Highcharts.chart(container, {
      chart: {
        type: 'column',
      },
      title: {
        text: 'Dynamic Bar Chart',
      },
      xAxis: {
        type: 'category',
      },
      yAxis: {
        title: {
          text: valueColumn.friendlyName,
        },
      },
      series,
    });
  },
};
```

**`src/onAdaptableReady.ts`**

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

const CHART_IN_LAYOUT_KEY = 'chartInLayout';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  const api = adaptableApi;

  const rowIndexCellRange: GridCellRange = {
    columnIds: ['name', 'github_stars'],
    rowIndexStart: 0,
    rowIndexEnd: 8,
  };

  api.gridApi.selectCellRange(rowIndexCellRange);
};
```

## Saving Charts

External charts can also be saved into [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

Similar to the [configuration for AG Grid Charts](https://www.adaptabletools.com/docs/handbook-charts-configuring/index.md), External Charts can be:

- defined in Initial Adaptable State (i.e. configured at design-time)
- created at run-time and then saved into State to be available when the application restarts
- displayed in custom locations provided by the users

**Example: Saving External Charts**

Using an external chart library with Adaptable State

- This example shows how External Charts can be saved into [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md) and then displayed in AdapTable
- 2 external (Highcharts) charts are defined in [Initial Adaptable State](https://www.adaptabletools.com/docs/technical-reference-initial-state/index.md):
  - Github Stars Line Chart
  - Frameworks Pie
- 2 custom Charting Containers are defined in [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md):
  - Above Grid
  - Below Grid
- `externalChartingOptions` wires show, hide, and preview behaviour to the Highcharts service (see `adaptableOptions.ts`)

- In the Charting Toolbar select an External Chart and a Container
- Click the `Show Chart` (Eye icon) button to display / hide the Charts

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  chartingService.ts
  columnDefs.ts        [template]
  gridOptions.ts
  icons.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + highcharts
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  ContextMenuContext,
  CustomContextMenuContext,
  SelectedCellInfo,
  UserContextMenuItem,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {chartIcon, pieIcon, lineChartIcon, barChartIcon} from './icons';
import {ChartingService, ChartModel} from './chartingService';

const chartingService = new ChartingService();

/**
 * Selection is valid only when:
 * - two columns are selected
 * - one is numeric and the other text
 */
const isSelectionValidForSimpleCharts = (selection: SelectedCellInfo) => {
  // Two columns need to be selected
  if (selection.columns.length !== 2) {
    return false;
  }
  // At least one is numeric
  const oneColumnIsNumeric =
    selection.columns.filter(column => column.dataType === 'number').length ===
    1;
  if (!oneColumnIsNumeric) {
    return false;
  }
  // At least one text
  const oneColumnIsText =
    selection.columns.filter(column => column.dataType === 'text').length === 1;
  if (!oneColumnIsText) {
    return false;
  }

  return true;
};

const contextMenuOptions: AdaptableOptions['contextMenuOptions'] = {
  customContextMenu: (context: CustomContextMenuContext) => {
    const {defaultAgGridMenuStructure, defaultAdaptableMenuStructure} = context;

    const chartMenuItem: UserContextMenuItem = {
      menuType: 'User',
      label: 'Show Charts',
      icon: {
        element: chartIcon,
      },
      subMenuItems: [
        {
          menuType: 'User',
          label: 'Pie Chart',
          icon: {element: pieIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            const chartModel = chartingService.showPieChart(selection);

            menuContext.adaptableApi.chartingApi.addExternalChartDefinition({
              Name: 'Pie Chart',
              Data: chartModel,
            });
          },
        },
        {
          menuType: 'User',
          label: 'Line Chart',
          icon: {element: lineChartIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            const chartModel = chartingService.showLineChart(selection);

            menuContext.adaptableApi.chartingApi.addExternalChartDefinition({
              Name: 'Chart-Name',
              Data: chartModel,
            });
          },
        },
        {
          menuType: 'User',
          label: 'Bar Chart',
          icon: {element: barChartIcon},
          onClick: (menuContext: ContextMenuContext) => {
            const selection =
              menuContext.adaptableApi.gridApi.getSelectedCellInfo();
            const chartModel = chartingService.showBarChart(selection);

            menuContext.adaptableApi.chartingApi.addExternalChartDefinition({
              Name: 'Pie Chart',
              Data: chartModel,
            });
          },
        },
      ],
    };

    return [
      chartMenuItem,
      '-',
      ...defaultAgGridMenuStructure,
      '-',
      ...defaultAdaptableMenuStructure,
    ];
  },
};

const chartingOptions: AdaptableOptions['chartingOptions'] = {
  chartContainers: [
    {
      name: 'Above Grid',
      element: 'demoOutputAbove',
    },
    {
      name: 'Below Grid',
      element: 'demoOutputBelow',
    },
  ],
  externalChartingOptions: {
    /**
     * This indicates to Adaptable if a chart is rendered or not.
     * This status is used to call the corect handlers when showing/hiding a chart.
     */
    isChartOpened: ({adaptableApi, chartDefinition}) => {
      const chartModel = chartDefinition?.Data as ChartModel;
      return chartingService.isChartOpened(chartModel.chartId);
    },
    /**
     * This is called when the user clicks the eye button next to the chart.
     */
    onHideChart: ({adaptableApi, chartDefinition}) => {
      const chartModel = chartDefinition.Data as ChartModel;
      chartingService.destroyChart(chartModel.chartId);
    },
    /**
     * This is called when the user clicks the eye button next to the chart.
     */
    onShowChart: ({adaptableApi, chartDefinition, container}) => {
      const chartModel = chartDefinition.Data as ChartModel;
      chartingService.restoreChart(chartModel, container?.element);
    },
    /**
     * This is called when the user deltes a chart from from adaptable.
     * We may want to hide the chart when it is deleted.
     */
    onDeleteChart: ({adaptableApi, chartDefinition}) => {
      const chartModel = chartDefinition.Data as ChartModel;
      if (chartingService.isChartOpened(chartModel.chartId)) {
        chartingService.destroyChart(chartModel.chartId);
      }
    },
    /**
     * Preview charts are transient charts, these charts should not be saved in state.
     * They are rendered in preivews.
     *
     * The returned object is passed to 'onHideChart'.
     * The returned object needs to have enough information to identify the instance of the chart.
     * This is important because we want to destory the chart when the preview is closed.
     */
    onPreviewChart: ({adaptableApi, chartDefinition, container}) => {
      const chartModel = chartDefinition.Data as ChartModel;
      return {
        Name: 'Preview Chart',
        Data: chartingService.previewChart(chartModel, container?.element),
      };
    },
  },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Saving External Charts',
  contextMenuOptions,
  chartingOptions,
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Charting',
          Toolbars: ['Charting'],
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'github_watchers',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
    Charting: {
      ExternalChartDefinitions: [
        {
          Name: 'Github Stars Line chart',
          Data: {
            options: {
              chart: {
                type: 'line',
              },
              title: {
                text: 'Dynamic Simple Line Chart',
                align: 'left',
              },
              yAxis: {
                title: {
                  text: 'Name',
                },
              },
              xAxis: {
                categories: [
                  'react',
                  'angular',
                  'vue',
                  'svelte',
                  'alpine',
                  'lit',
                  'stimulus',
                  'ember.js',
                  'stencil',
                ],
              },
              legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
              },
              plotOptions: {
                series: {
                  label: {
                    connectorAllowed: false,
                  },
                },
              },
              series: [
                {
                  name: 'Name and GitHub Stars',
                  data: [
                    179429, 78348, 191435, 53935, 19338, 9752, 11049, 22093,
                    9884,
                  ],
                },
              ],
              responsive: {
                rules: [
                  {
                    condition: {
                      maxHeight: 300,
                    },
                    chartOptions: {
                      legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom',
                      },
                    },
                    _id: 'highcharts-c73e53c-14',
                  },
                ],
              },
            },
            chartId: 'CHART_ID_1696840189274',
          },
          Uuid: '80da73bd-75e4-4371-a7f9-7ba518cb9113',
        },
        {
          Name: 'Frameworks Pie chart',
          Data: {
            options: {
              chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie',
              },
              title: {
                text: 'Dynamic Simple Pie Chart',
                align: 'left',
              },
              tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
              },
              accessibility: {
                point: {
                  valueSuffix: '%',
                },
              },
              plotOptions: {
                pie: {
                  allowPointSelect: true,
                  cursor: 'pointer',
                  dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                  },
                },
              },
              series: [
                {
                  name: 'Name',
                  colorByPoint: true,
                  data: [
                    {
                      name: 'angular',
                      y: 78348,
                    },
                    {
                      name: 'vue',
                      y: 191435,
                    },
                    {
                      name: 'svelte',
                      y: 53935,
                    },
                    {
                      name: 'alpine',
                      y: 19338,
                    },
                    {
                      name: 'lit',
                      y: 9752,
                    },
                    {
                      name: 'stimulus',
                      y: 11049,
                    },
                    {
                      name: 'ember.js',
                      y: 22093,
                    },
                    {
                      name: 'stencil',
                      y: 9884,
                    },
                    {
                      name: 'solid',
                      y: 13119,
                    },
                  ],
                },
              ],
            },
            chartId: 'CHART_ID_1696840216341',
          },
          Uuid: '19f72754-c322-4b23-b4f5-2fca05a0132b',
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/icons.ts`**

```ts
export const chartIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M3 21V17M9 21V13M15 21V15M21 21V11M8.43934 5.56066C8.71079 5.83211 9.08579 6 9.5 6C9.91421 6 10.2892 5.83211 10.5607 5.56066M8.43934 5.56066C8.16789 5.28921 8 4.91421 8 4.5C8 3.67157 8.67157 3 9.5 3C10.3284 3 11 3.67157 11 4.5C11 4.91421 10.8321 5.28921 10.5607 5.56066M8.43934 5.56066L5.56066 8.43934M5.56066 8.43934C5.28921 8.16789 4.91421 8 4.5 8C3.67157 8 3 8.67157 3 9.5C3 10.3284 3.67157 11 4.5 11C5.32843 11 6 10.3284 6 9.5C6 9.08579 5.83211 8.71079 5.56066 8.43934ZM10.5607 5.56066L13.4393 8.43934M13.4393 8.43934C13.1679 8.71079 13 9.08579 13 9.5C13 10.3284 13.6716 11 14.5 11C15.3284 11 16 10.3284 16 9.5C16 9.08579 15.8321 8.71079 15.5607 8.43934M13.4393 8.43934C13.7108 8.16789 14.0858 8 14.5 8C14.9142 8 15.2892 8.16789 15.5607 8.43934M15.5607 8.43934L18.4393 5.56066M18.4393 5.56066C18.7108 5.83211 19.0858 6 19.5 6C20.3284 6 21 5.32843 21 4.5C21 3.67157 20.3284 3 19.5 3C18.6716 3 18 3.67157 18 4.5C18 4.91421 18.1679 5.28921 18.4393 5.56066Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;

export const pieIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M6.4443 3.6853C6.97115 3.33327 7.52766 3.03383 8.10577 2.7894C9.50868 2.19627 10.2101 1.8997 11.1051 2.49296C12 3.08623 12 4.05748 12 6V8C12 9.88561 12 10.8284 12.5858 11.4142C13.1716 12 14.1144 12 16 12H18C19.9425 12 20.9138 12 21.507 12.8949C22.1003 13.7899 21.8037 14.4913 21.2106 15.8942C20.9662 16.4723 20.6667 17.0288 20.3147 17.5557C19.2159 19.2002 17.6541 20.4819 15.8268 21.2388C13.9996 21.9957 11.9889 22.1937 10.0491 21.8078C8.10929 21.422 6.32746 20.4696 4.92894 19.0711C3.53041 17.6725 2.578 15.8907 2.19215 13.9509C1.8063 12.0111 2.00433 10.0004 2.76121 8.17316C3.51809 6.3459 4.79981 4.78412 6.4443 3.6853Z" fill="#1C274C"/>
  <path fill-rule="evenodd" clip-rule="evenodd" d="M13.7739 2.12812C13.8771 1.72698 14.286 1.48549 14.6871 1.58873C18.4658 2.56129 21.4389 5.53443 22.4115 9.31307C22.5147 9.71421 22.2732 10.1231 21.8721 10.2263C21.4709 10.3296 21.0621 10.0881 20.9588 9.68696C20.1225 6.43757 17.5626 3.87772 14.3132 3.04139C13.9121 2.93814 13.6706 2.52926 13.7739 2.12812Z" fill="#1C274C"/>
</svg>
`;

export const lineChartIcon = `
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M21 21H7.8C6.11984 21 5.27976 21 4.63803 20.673C4.07354 20.3854 3.6146 19.9265 3.32698 19.362C3 18.7202 3 17.8802 3 16.2V3M6 15L10 11L14 15L20 9M20 9V13M20 9H16" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;

export const barChartIcon = `
<?xml version="1.0" encoding="utf-8"?>
  <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M3.29289 9.29289C3 9.58579 3 10.0572 3 11V17C3 17.9428 3 18.4142 3.29289 18.7071C3.58579 19 4.05719 19 5 19C5.94281 19 6.41421 19 6.70711 18.7071C7 18.4142 7 17.9428 7 17V11C7 10.0572 7 9.58579 6.70711 9.29289C6.41421 9 5.94281 9 5 9C4.05719 9 3.58579 9 3.29289 9.29289Z" fill="#1C274C"/>
  <path opacity="0.4" d="M17.2929 2.29289C17 2.58579 17 3.05719 17 4V17C17 17.9428 17 18.4142 17.2929 18.7071C17.5858 19 18.0572 19 19 19C19.9428 19 20.4142 19 20.7071 18.7071C21 18.4142 21 17.9428 21 17V4C21 3.05719 21 2.58579 20.7071 2.29289C20.4142 2 19.9428 2 19 2C18.0572 2 17.5858 2 17.2929 2.29289Z" fill="#1C274C"/>
  <path opacity="0.7" d="M10 7C10 6.05719 10 5.58579 10.2929 5.29289C10.5858 5 11.0572 5 12 5C12.9428 5 13.4142 5 13.7071 5.29289C14 5.58579 14 6.05719 14 7V17C14 17.9428 14 18.4142 13.7071 18.7071C13.4142 19 12.9428 19 12 19C11.0572 19 10.5858 19 10.2929 18.7071C10 18.4142 10 17.9428 10 17V7Z" fill="#1C274C"/>
  <path d="M3 21.25C2.58579 21.25 2.25 21.5858 2.25 22C2.25 22.4142 2.58579 22.75 3 22.75H21C21.4142 22.75 21.75 22.4142 21.75 22C21.75 21.5858 21.4142 21.25 21 21.25H3Z" fill="#1C274C"/>
</svg>
`;
```

**`src/chartingService.ts`**

```ts
import {SelectedCellInfo} from '@adaptabletools/adaptable';
import * as Highcharts from 'highcharts';

/**
 * This service is an example on how one would integrate an external charting library with Adaptable.
 *
 * It is a statefull service, it keep track of the chart instances and their location.
 * Using this state it knows which charts are open and allows it to control them.
 */

const container = 'demoOutputAbove';

/**
 * This is used to generate unique ids for the charts.
 */
const getUniqueID = () => {
  return `CHART_ID_${Date.now()}`;
};

/**
 * Prepares data for the charts.
 *
 * Takes the selection and returns the data grouped in two sets:
 * - categories: the text column values
 * - values: the numeric values
 */
const getCategoriesAndValuesFromSelection = (selection: SelectedCellInfo) => {
  const [col1, col2] = selection.columns;

  // Select the string column as the category column
  const categoryColumn = col1.dataType === 'text' ? col1 : col2;
  const valueColumn = col1.dataType === 'number' ? col1 : col2;

  // Group the selected cells in sets of  [category-name, value]
  const categoryValueSets: [string, number][] = [];
  for (let categoryCell of selection.gridCells) {
    if (categoryCell.column.columnId === categoryColumn.columnId) {
      // find corresponding value
      const valueCell = selection.gridCells.find(localGridCell => {
        return (
          localGridCell.rowNode.id === categoryCell.rowNode.id &&
          // and not the same column
          localGridCell.column.columnId !== categoryCell.column.columnId
        );
      });
      if (valueCell) {
        categoryValueSets.push([categoryCell.rawValue, valueCell.rawValue]);
      }
    }
  }
  const categories = categoryValueSets.map(([category]) => category);
  const values = categoryValueSets.map(([category, value]) => value);
  return {categories, values, categoryColumn, valueColumn, categoryValueSets};
};

/**
 * This model is saved in adaptable state. This is all one needs to manage chart persistence.
 *
 */
export type ChartModel = {
  options: Highcharts.Options;
  /**
   * The chartId allows us to know if a persisted chart is opened or not.
   * When a chart is created a unique id is generated.
   */
  chartId: string;
};

export class ChartingService {
  /**
   * This map helps us to keep track of the chart instances.
   * To know which chart is opened in which container.
   */
  private chartInstances: Record<
    string,
    {
      location: string | HTMLElement;
      Instance: Highcharts.Chart;
    }
  > = {};

  // CHART INSTANCES MANAGEMENT

  /**
   * Checks if a chart is opened.
   * We consider that a chart instance can be open in only one location.
   *
   * It checkis the the chart id is in the chartInstances map.
   *
   * @param chartId unique chart id
   * @returns boolean
   */
  public isChartOpened(chartId: string): boolean {
    return !!this.getChart(chartId);
  }

  /**
   * Destroys a chart instance.
   *
   * @param chartId unique chart id
   */
  destroyChart(chartId: string) {
    const chartInstance = this.getChart(chartId);
    if (chartInstance) {
      chartInstance.Instance?.destroy?.();
      delete this.chartInstances[chartId];
    }
  }

  /**
   *
   * @param chartId unique chart id
   * @returns
   */
  private getChart(
    chartId: string
  ): {location: string | HTMLElement; Instance: Highcharts.Chart} | undefined {
    return this.chartInstances[chartId];
  }

  // CREATE CHARTS

  /**
   * An internal method to create charts and keep track of them.
   */
  private createChart(
    chartOptions: Highcharts.Options,
    options?: {
      location?: string | HTMLElement;
      chartId?: string;
      isPreview?: boolean;
    }
  ) {
    const location = options?.location ?? container;
    // For now just close all charts before opening a new one.
    // more complex logic needs to be implemented to allow multiple charts.
    this.closeAllChartsAtLocation(location);

    const chartId = options?.chartId ?? getUniqueID();

    const chartInstance = Highcharts.chart(location, chartOptions);

    this.chartInstances[chartId] = {
      location,
      Instance: chartInstance,
    };

    return {
      options: chartOptions,
      chartId,
    };
  }

  /**
   * It closes all charts at a given location.
   * This service supports only one chart per location.
   *
   * @param location chart location
   */
  private closeAllChartsAtLocation(location: string | HTMLElement) {
    Object.entries(this.chartInstances).forEach(
      ([chartId, {Instance, location: instanceLocation}]) => {
        if (instanceLocation === location) {
          if (Instance.destroy) {
            try {
              Instance.destroy?.();
            } catch (e) {
              console.error('Failed to destroy chart with id: ', chartId);
            }
          }
          delete this.chartInstances[chartId];
        }
      }
    );
  }

  /**
   * Recreates previously created charts.
   *
   * @param chartModel holds information about previous created chart
   * @param location location where the chart should be rendered to
   */
  restoreChart(chartModel: ChartModel, location?: string | HTMLElement) {
    const {options, chartId} = chartModel;
    return this.createChart(options, {chartId, location});
  }

  /**
   * The difference between this and restore is that it ignore the chartId.
   * This means it creates a new chart. This allows us to preview the chart
   *
   * @param chartModel holds information about previous created chart
   * @param location location where the chart should be rendered to
   */
  previewChart(chartModel: ChartModel, location?: string | HTMLElement) {
    const {options} = chartModel;
    return this.createChart(options, {location});
  }

  /**
   * Creates a line chart and returns the chart model.
   */
  public showLineChart(selection: SelectedCellInfo): ChartModel {
    const {categories, values, categoryColumn, valueColumn} =
      getCategoriesAndValuesFromSelection(selection);
    let valuesAny: any = values;
    const chartConfig: Highcharts.Options = {
      chart: {
        type: 'line',
        // height: 200,
      },
      title: {
        text: 'Dynamic Simple Line Chart',
        align: 'left',
      },
      yAxis: {
        title: {
          text: categoryColumn?.friendlyName,
        },
      },
      xAxis: {
        categories,
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false,
          },
        },
      },
      series: [
        //@ts-ignore
        {
          name: `${categoryColumn?.friendlyName} and ${valueColumn?.friendlyName}`,
          // @ts-ignore
          data: values,
        },
      ],
      responsive: {
        rules: [
          {
            condition: {
              maxHeight: 300,
            },
            chartOptions: {
              legend: {
                layout: 'horizontal',
                align: 'center',
                verticalAlign: 'bottom',
              },
            },
          },
        ],
      },
    };

    return this.createChart(chartConfig);
  }

  /**
   * Creates a pie chart and returns the chart model.
   */
  public showPieChart(selection: SelectedCellInfo): ChartModel {
    const {categoryColumn, categoryValueSets} =
      getCategoriesAndValuesFromSelection(selection);

    const series = categoryValueSets.map(([category, value]) => ({
      name: category,
      y: value,
    }));

    const config: Highcharts.Options = {
      chart: {
        // @ts-ignore
        plotBackgroundColor: null,
        // @ts-ignore
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
        // height: 200,
      },
      title: {
        text: 'Dynamic Simple Pie Chart',
        align: 'left',
      },
      tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
      },
      accessibility: {
        point: {
          valueSuffix: '%',
        },
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
          },
        },
      },
      series: [
        {
          name: categoryColumn.friendlyName,
          colorByPoint: true,
          data: series,
        } as any,
      ],
    };

    return this.createChart(config);
  }

  /**
   * Creates a bar chart and returns the chart model.
   */
  public showBarChart(selection: SelectedCellInfo): ChartModel {
    const {categoryColumn, valueColumn, categoryValueSets} =
      getCategoriesAndValuesFromSelection(selection);

    const config: Highcharts.Options = {
      chart: {
        type: 'column',
        // height: 200,
      },
      title: {
        text: 'Dynamic Bar Chart',
      },
      xAxis: {
        type: 'category',
      },
      yAxis: {
        title: {
          text: valueColumn.friendlyName,
        },
      },
      series: [
        {
          name: categoryColumn.friendlyName,
          data: categoryValueSets,
        } as any,
      ],
    };

    return this.createChart(config);
  }
}
```
