# FDC3 Demo App

Canonical page: https://www.adaptabletools.com/docs/handbook-fdc3-example

- This page describes a demo app that illustrates AdapTable's FDC3 capability
- The app leverages the first-rate [Connectifi Sandbox](https://apps.connectifi-interop.com/sandbox) which can be used for testing FDC3

FDC3 is all about interopability with **external** applications and widgets.

For this reason, its not possible to provide an isolated demo of FDC3 features in AdapTable, in the same way we can for all other AdapTable Modules.

Instead this page walks through an existing FDC3 Demo that illustrates some of AdapTable's FDC3 functionality.

- To run the demo click this [link](https://apps.connectifi-interop.com/sandbox) and then select AdapTable
- The demo code is available [here](https://github.com/AdaptableTools/connectifi-fdc3-demo) with this [ReadMe](https://github.com/AdaptableTools/connectifi-fdc3-demo/blob/master/README.md)

## Demo Introduction

In the demo app we illustrate how AdapTable users are able to:

- Raise FDC3 Intents
- Listen for FDC3 Intents
- Broadcast FDC3 Context
- Listen for FDC3 Context
- Raise a Custom FDC3 Intent
- Define FDC3 Action Buttons, Action Columns and Context Menu Items

<Illustration alt="AdaptableState Sequence Diagram" src="/images/docs/fdc3-app-demo.jpeg" />

- The demo app primarily uses the [FDC3 Instrument Context](https://fdc3.finos.org/docs/context/ref/Instrument) to manage Intents and Context
- But all FDC3 context types are available out of the box in AdapTable

The demo leverages the excellent - and free(!) - [Connectifi Sandbox](https://apps.connectifi-interop.com/sandbox) as the desktop agent

The data in the app is purely meaningless **dummy data** for illustration purposes; only the Tickers are real

## Demo Step by Step

Here are the key steps performed by the demo to leverage AdapTable's FDC3 functionality:

### Creating the demo FDC3 app

Create [FDC3 Data Mapping](https://www.adaptabletools.com/docs/handbook-fdc3-mappings/index.md) - to [FDC3 Instrument Context](https://fdc3.finos.org/docs/context/ref/Instrument):

- Use `Name` column (defined by '\_colId') as the Instrument Nam3
- Use `Symbol` field (defined by '\_field') to map to Ticker (in `id` prop)

```tsx {2}
fdc3Options: {
  gridDataContextMapping: {
    'fdc3.instrument': {
      name: '_colId.Name',
      id: { ticker: '_field.Symbol' },
    },
  },
}
```

- Mappings provide the “glue” to map AG Grid’s data and columns to required FDC3 behaviour
- AdapTable looks at the mappings to work out which columns to use when creating Intents and Contexts
- This app has just one mapping but there is no limit to how many can be provided

The demo app raises 3 FDC3 Intents - defined in the `raises` property in the `intents` section:

- `ViewChart`
- `ViewNews`
- `ViewInstrument`

It provides an Action Button definition for each Intent to be raised.

These will then be rendered in the default FDC3 Action Column.

The key for each item is the name of the Intent being raised.

The app also raises a Custom Intent which is discussed below

```ts {1,2,13,24}
raises: {
   ViewChart: [
    {
      contextType: 'fdc3.instrument',
      actionButton: {
        id: 'viewChartBtn',
        tooltip: 'Raise: ViewChart',
        icon: '_defaultFdc3',
        buttonStyle: { tone: 'info', variant: 'outlined' },
      },
    },
  ],
  ViewNews: [
    {
      contextType: 'fdc3.instrument',
      actionButton: {
        id: 'viewNewsBtn',
        tooltip: 'Raise: ViewNews',
        icon: '_defaultFdc3',
        buttonStyle: { variant: 'outlined', tone: 'warning' },
      },
    },
  ],
  ViewInstrument: [
    {
      contextType: 'fdc3.instrument',
      actionButton: {
        id: 'viewInstrumentBtn',
        tooltip: 'Raise: ViewInstrument',
        icon: { name: 'visibility-on' },
        buttonStyle: { tone: 'error', variant: 'outlined' },
      },
    },
  ],
},
```

Intents are listened for using the `listensFor` property (in the `intents` section)

The demo app listens for the `ViewInstrument` Intent and provides an accompanying implementation of the `handleIntent` property which:

- jumps to, and highlights in yellow for 5 seconds, the row which contains the instrument (using [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md))
- sends a [System Status Message](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md) displaying the Context received

```ts {1,3}
listensFor: ['ViewInstrument'],

handleIntent: (handleFDC3Context: HandleFdc3Context) => {
  const adaptableApi: AdaptableApi = handleFDC3Context.adaptableApi;
  const ticker = handleFDC3Context.context.id?.ticker;

  // Create Row Highlight object, then jump to Row and higlight it
  const rowHighlightInfo: RowHighlightInfo = {
    primaryKeyValue: ticker,
    timeout: 5000,
    highlightStyle: { BackColor: 'var(--ab-color-palette-21)', ForeColor: 'var(--ab-color-palette-13)' },
  };
  adaptableApi.gridApi.jumpToRow(ticker);
  adaptableApi.gridApi.highlightRow(rowHighlightInfo);

  // Display Info System Status Message with details of Intent received
  adaptableApi.systemStatusApi.setInfoSystemStatus(
    'Intent Received: ' + ticker,
    JSON.stringify(handleFDC3Context.context),
  );
},
```

The FDC3 Context is broadcast using the `broadcasts` property:

The demo app Broadcasts FDC3 Instrument Context in 2 ways:

- using Context Menu Items in the `Name` and `Ticker` columns
- via an FDC3 Action Button - which will be rendered in the default FDC3 Action Column

The key for each item is the Context mapping created in FDC3 Grid Data Mappings (in Stage 1)

```ts {1,2}
broadcasts: {
  'fdc3.instrument': {
    contextMenu: {
      columnIds: ['Ticker', 'Name'],
      icon: '_defaultFdc3',
    },
    actionButton: {
      id: 'broadcastInstrumentBtn',
      icon: { name: 'broadcast' },
      tooltip: `Broadcast: Instrument`,
      buttonStyle: { tone: 'success', variant: 'outlined' },
    },
  },
},
```

The demo app listens for the `fdc3.instrument` Context, using the `listensFor` property.

As is typically the case, this property is accompanied by an implementation of the `handleContext` property which performs any necesary accompanying behaviour.

In the demo app, the function is used to:

- [Filter](https://www.adaptabletools.com/docs/handbook-column-filter/index.md) the Grid using the Ticker received in the Context
- send a [System Status Message](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md) displaying the Context received

```ts {1,3}
listensFor: ['fdc3.instrument'],

handleContext: (handleFDC3Context: HandleFdc3Context) => {
  if (handleFDC3Context.context.type === 'fdc3.instrument') {
    const adaptableApi: AdaptableApi = handleFDC3Context.adaptableApi;
    const ticker = handleFDC3Context.context.id?.ticker;
    // Filter the Grid using the received Ticker
    adaptableApi.filterApi.columnFilterApi.setColumnFilterForColumn('Ticker', {
      PredicateId: 'Is',
      PredicateInputs: [handleFDC3Context.context.id?.ticker],
    });
    // Display Success System Status Message with details of Context received
    adaptableApi.systemStatusApi.setSuccessSystemStatus(
      'Context Received: ' + ticker,
      JSON.stringify(handleFDC3Context.context),
    );
  }
},
```

AdapTable fully supports Custom FDC3.

In this app we raise a Custom `GetPrice` intent.

This integrates with functionality provided by the [Connectifi Sandbox](https://apps.connectifi-interop.com/sandbox) to illustrate usage of custom FDC3

The demo app uses Custom FDC3 context as follow:

- defines the Custom Intent to raise in the `custom` property in the `intents` section
- provides the name of the Custom Intent to raise as the key (here `GetPrice`)
- supplies a context type of `fdc3.instrument`, which matches the Grid Data Mappings previously defined
- defines a bespoke Action Column definition (which AdapTable will render as a separate column)
- provides an implementation for the `handleIntentResolution` property (which is typically provided when raising Custom Intents)
- the function replaces the Action Column button with the result (here a Price) returned from the Intent

```ts {1,2,32}
custom: {
  GetPrice: [
    {
      contextType: 'fdc3.instrument',
      actionColumn: {
        columnId: 'fdc3GetPriceColumn',
        friendlyName: 'Get Price',
        button: {
          id: 'GetPriceButton',
          label: (button, context) => {
            const price = priceMap.get(context.rowData.Symbol);
            return !!price ? `$ ${price}` : 'Get Price';
          },
          icon: (button, context) => {
            const price = priceMap.get(context.rowData.Symbol);
            return !price ? { name: 'quote' } : null;
          },
          tooltip: (button, context) => {
            return `Get Price Info for ${context.rowData.Symbol}`;
          },
          buttonStyle: (button, context) => {
            return priceMap.has(context.rowData.Symbol)
              ? { tone: 'success', variant: 'text', }
              : { tone: 'info', variant: 'outlined', };
          },
          disabled: (button, context) => {
            return priceMap.has(context.rowData.Symbol);
          },
        },
      },
      // Handle intent resolution by showing returned Price in Column
      handleIntentResolution: async (
        context: HandleFdc3IntentResolutionContext,
      ) => {
        const result = await context.intentResolution.getResult();
        if (!result?.type) { return; }
        const api: AdaptableApi = context.adaptableApi;
        const contextData = intentResult as Fdc3CustomContext;
        const ticker = contextData.id?.ticker;
        const price = contextData.price;
        if (ticker) { priceMap.set(ticker, price) }
        api.gridApi.refreshColumn('fdc3GetPriceColumn');
      },
    },
  ],
},
```

The demo uses all 3 FDC3 UI components that AdapTable provides:

- Intents are raised using FDC3 Action Buttons
- The Custom Intent is displayed in a bespoke [FDC3 Action Column](https://www.adaptabletools.com/docs/handbook-fdc3-ui-components/index.md)
- Context is broadcast using FDC3 [Context Menu](https://www.adaptabletools.com/docs/ui-context-menu/index.md) Items

The demo app overrides the default FDC3 Action column properties set by AdapTable to make the column narrower than the default.

```ts {2}
// Narrow width of Default Action Column
actionColumnDefaultConfiguration: {
  width: 150,
},
```

Both the **default** FDC3 Action Column and **bespoke** FDC3 Action Columns must be referenced in a Layout.

Hence the demo app lists them in the `TableColumns` property in the [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md).

```ts {9,11}
Layout: {
  CurrentLayout: 'Table Layout',
  Layouts: [
    Name: 'Table Layout',
    TableColumns: [
      'Ticker',
      'Name',
      'Price',
      'fdc3GetPriceColumn', // Bespoke FDC3 Action Column
      'Position',
      'fdc3ActionColumn', // Default FDC3 Action Column
      'Sector',
      'SectorPnl',
    ],
  },
 ],
},
```

## Other AdapTable Objects

The demo app contains a few other AdapTable [Initial Adaptable State sections](https://www.adaptabletools.com/docs/technical-reference-initial-state/index.md) and [Adaptable Options properties](https://www.adaptabletools.com/docs/technical-reference-adaptable-options/index.md) to create a more pleasing and realistic visual effect. These include:

- [Theme](https://www.adaptabletools.com/docs/handbook-theming/index.md) - app demo uses the dark theme
- [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md) - added a Demo Info panel which describes this app
- [Dashboard](https://www.adaptabletools.com/docs/ui-dashboard/index.md) - set the app's Title, provided some buttons including a custom Info button, which opens Demo Info panel described above
- [Status Bar](https://www.adaptabletools.com/docs/ui-status-bar/index.md) - added Layout and Cell Summary panels
- lots of [Column Formats](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) - particularly on the number columns
- a [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) - called `Sector Pnl` which aggregates all the Postions, grouped by Sector
- 2 [Layouts](https://www.adaptabletools.com/docs/handbook-layouts/index.md): `Table Layout` and `Sector Layout` (with Row Grouping and Aggregations)
- [Badge Style](https://www.adaptabletools.com/docs/handbook-styled-column-badge/index.md) - on the Sector column
- [Sparkline Column](https://www.adaptabletools.com/docs/handbook-styled-column-sparkline/index.md) - on the Performance column
- in [Context Menu Options](https://www.adaptabletools.com/docs/ui-context-menu/index.md) - provided implementation for `customContextMenu` so only one item appears in Ticker Column's context menu

### Putting It All Together

This is the full definition of the FDC3 Options used in the demo:

```ts {1}
fdc3Options: {
  enableLogging: true,
  // Create a single Data Mapping - to FDC3 Instrument Context
  // Use `Name` column (defined by '_colId') as the Instrument Name
  // Use the `Symbol` field (defined by '_field') to map to Ticker (in `id` prop)
  gridDataContextMapping: {
    'fdc3.instrument': {
      name: '_colId.Name',
      id: {
        ticker: '_field.Symbol',
      },
    },
  },
  intents: {
    raises: {
      // Raise 3 Intents: `ViewChart`, `ViewNews` and `ViewInstument`
      // Create an FDC3 Action Button for all 3 Intents
      // Each button will be rendered in the default FDC3 Action Column
      // Note: All 3 Intents use the mapping that was created in `gridDataContextMapping`
      ViewChart: [
        {
          contextType: 'fdc3.instrument',
          actionButton: {
            id: 'viewChartBtn',
            tooltip: 'Raise: ViewChart',
            icon: '_defaultFdc3',
            buttonStyle: {
              tone: 'info',
              variant: 'outlined',
            },
          },
        },
      ],
      ViewNews: [
        {
          contextType: 'fdc3.instrument',
          actionButton: {
            id: 'viewNewsBtn',
            tooltip: 'Raise: ViewNews',
            icon: '_defaultFdc3',
            buttonStyle: {
              variant: 'outlined',
              tone: 'warning',
            },
          },
        },
      ],
      ViewInstrument: [
        {
          contextType: 'fdc3.instrument',
          actionButton: {
            id: 'viewInstrumentBtn',
            tooltip: 'Raise: ViewInstrument',
            icon: {
              name: 'visibility-on',
            },
            buttonStyle: {
              tone: 'error',
              variant: 'outlined',
            },
          },
        },
      ],
      custom: {
        // Raise the Custom `GetPrice` Intent - using a bespoke FDC3 Action Column
        // When we receive a Price, display it in the column (instead of the button)
        GetPrice: [
          {
            contextType: 'fdc3.instrument',
            // Provide a bespoke Action Column definition
            actionColumn: {
              columnId: 'fdc3GetPriceColumn',
              friendlyName: 'Get Price',
              button: {
                id: 'GetPriceButton',
                label: (button, context) => {
                  const price = priceMap.get(context.rowData.Symbol);
                  return !!price ? `$ ${price}` : 'Get Price';
                },
                icon: (button, context) => {
                  const price = priceMap.get(context.rowData.Symbol);
                  return !price
                    ? {
                        name: 'quote',
                      }
                    : null;
                },
                tooltip: (button, context) => {
                  return `Get Price Info for ${context.rowData.Symbol}`;
                },
                buttonStyle: (button, context) => {
                  return priceMap.has(context.rowData.Symbol)
                    ? {
                        tone: 'success',
                        variant: 'text',
                      }
                    : {
                        tone: 'info',
                        variant: 'outlined',
                      };
                },
                disabled: (button, context) => {
                  return priceMap.has(context.rowData.Symbol);
                },
              },
            },
            // Handle the intent resolution by showing the returned Price in the Column
            handleIntentResolution: async (
              handleResolutionContext: HandleFdc3IntentResolutionContext,
            ) => {
              const intentResult =
                await handleResolutionContext.intentResolution.getResult();
              if (!intentResult?.type) {
                return;
              }
              const adaptableApi: AdaptableApi =
                handleResolutionContext.adaptableApi;
              const contextData = intentResult as Fdc3CustomContext;
              const ticker = contextData.id?.ticker;
              const price = contextData.price;
              if (ticker) {
                priceMap.set(ticker, price);
              }
              adaptableApi.gridApi.refreshColumn('fdc3GetPriceColumn');
            },
          },
        ],
      },
    },

    // listen for the 'fdc3.instrument' Context
    listensFor: ['ViewInstrument'],

    // handle the Intent received
    handleIntent: (handleFDC3Context: HandleFdc3Context) => {
      const adaptableApi: AdaptableApi = handleFDC3Context.adaptableApi;
      const ticker = handleFDC3Context.context.id?.ticker;
      const upperTicker = ticker.toUpperCase();

      // Create Row Highlight object, then jump to row and highlight it
      const rowHighlightInfo: RowHighlightInfo = {
        primaryKeyValue: upperTicker,
        timeout: 5000,
        highlightStyle: {
          BackColor: 'var(--ab-color-palette-21)',
          ForeColor: 'var(--ab-color-palette-13)',
        },
      };
      adaptableApi.gridApi.jumpToRow(upperTicker);
      adaptableApi.gridApi.highlightRow(rowHighlightInfo);

      // Display `Info` System Status Message with details of Intent received
      adaptableApi.systemStatusApi.setInfoSystemStatus(
        'Intent Received: ' + upperTicker,
        JSON.stringify(handleFDC3Context.context),
      );
    },
  },
  contexts: {
    // Broadcast FDC3 Instrument in 2 ways:
    // using a Context Menu Item in Ticker and Name columns
    // via a FDC3 Action Button (which will be rendered in the default FDC3 Action Column)
    // Note: The Context uses the mapping that was created in `gridDataContextMapping`
    broadcasts: {
      'fdc3.instrument': {
        contextMenu: {
          columnIds: ['Ticker', 'Name'],
          icon: '_defaultFdc3',
        },
        actionButton: {
          id: 'broadcastInstrumentBtn',
          icon: { name: 'broadcast' },
          tooltip: `Broadcast: Instrument`,
          buttonStyle: {
            tone: 'success',
            variant: 'outlined',
          },
        },
      },
    },

    // listen for the `ViewInstrument` Context
    listensFor: ['fdc3.instrument'],

    // handle the Context received
    handleContext: (handleFDC3Context: HandleFdc3Context) => {
      if (handleFDC3Context.context.type === 'fdc3.instrument') {
        const adaptableApi: AdaptableApi = handleFDC3Context.adaptableApi;
        const ticker = handleFDC3Context.context.id?.ticker;

        // Filter the Grid using the received Ticker
        adaptableApi.filterApi.columnFilterApi.setColumnFilterForColumn('Ticker', {
          PredicateId: 'Is',
          PredicateInputs: [handleFDC3Context.context.id?.ticker],
        });

        // Display `Success` System Status Message with details of Context received
        adaptableApi.systemStatusApi.setSuccessSystemStatus(
          'Context Received: ' + ticker,
          JSON.stringify(handleFDC3Context.context),
        );
      }
    },
  },

  // Narrow width of Default Action Column
  actionColumnDefaultConfiguration: {
    width: 150,
  },
},

```
