# Alert Message

Canonical page: https://www.adaptabletools.com/docs/handbook-alerting-message

- AdapTable dynamically creates an Alert Message (containing Header and Text) each time an Alert is triggered
- This Alert Message can be overridden by users who can provide custom text; this can be done in 2 ways:
  - via the Alert Definition
  - using Alert Options

When an Alert fires, AdapTable provides an accompaying message describing why it was triggered.

This Alert Message - is created by AdapTable automatically - and is formed of 2 parts:

- Alert **Header** - a brief description of the Alert
- Alert **Text** - more information about what took place to trigger the Alert

- The Alert Message is displayed in **all** the Alert related UI controls
- i.e. in the Toolbar, Tool Panel, Status Bar - and most notably in the [Alert Notification](https://www.adaptabletools.com/docs/handbook-alerting-notifications/index.md)

## Custom Alert Message 

As noted above, AdapTable will create the Alert Message automatically, based on the Alert Definition and the action that triggered the Alert.

However users are able to **override** this behaviour and to supply a custom Alert Message.

This bespoke Alert Message can be provide in 2 different ways:

- as properties in the Alert Definition (run-time or design-time)
- via a function in Alert Options (design-time only)

### Alert Definition

The most straightforward way to override the automated Alert Message is via the Alert Definition.

There are 2 properties that can be provided:

- `MessageHeader` - allows a custom Header to be displayed
- `MessageText` - allows custom Text to be shown in the Message

These properties are available both to the developer at design time and the end user at run-time

**Example: Custom Alert Messages (Definition)**

Providing Custom Alert Message via Alert Definition

- This demo shows how to provide a Custom Alert Message Header and Text using the Alert Definition
- A `Warning` Alert fires any time a value is changed in the `Language` Column
- We provide a Custom Header and Message in the Alert Definition
### Expand to see the Alert Definition

```ts
Alert: {
  AlertDefinitions: [
    {
      Name: 'alert-language',
      MessageType: 'Warning',
      Scope: {
        ColumnIds: ['language'],
      },
      Rule: 'ANY_CHANGE()',
      MessageHeader: 'A Change was made!!!',
      MessageText: 'The user just changed the value in the Language Column',
      AlertProperties: {
        DisplayNotification: true,
      },
    },
  ],
},
```

- Edit a cell in the `Language` Column and see the Alert with the custom Header and Text messages
- Note: The text displayed is the same every time the Alert fires (regardless of the row)

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
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, AlertMessageContext} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Alert Message - Definition',
  initialState: {
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-language',
          MessageType: 'Warning',
          Scope: {
            ColumnIds: ['language'],
          },
          Rule: 'ANY_CHANGE()',
          MessageHeader: 'A Change was made!!!',
          MessageText: 'The user just changed the value in the Language Column',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: ['name', 'language', 'license', 'has_wiki'],
        },
      ],
    },
  },
};
```

### Messages using Templates

The Custom Alert Message in the Alert Definition can be provided with Template Literals.

AdapTable automatically **replaces** these templates, using string interpolation, with the relevant text when the Alert Message displays.

This enables the Alert Message to display "dynamic" content, that changes for each Alert.

Template Literals can be used in both parts of the Alert Message: Header and Text

AdapTable provides two sets of Message Templates - one which can be used in both [Data Change](https://www.adaptabletools.com/docs/handbook-alerting-data-change/index.md) and [Aggregation](https://www.adaptabletools.com/docs/handbook-alerting-aggregation/index.md) Alerts, and the other which is designed for [Row Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md):

| Template Literal         | Description                                                                                                   | Data Change & Aggregation | Row Change |
| ------------------- | ------------------------------------------------------------------------------------------------------------- | :-----------------------: | :--------: |
| `[newValue]`        | New value for changed cell                                                                                    |             ✅             |     ❌      |
| `[oldValue]`        | Old value for changed cell                                                                                    |             ✅             |     ❌      |
| `[column]`          | Name of Changed Column                                                                                        |             ✅             |     ❌      |
| `[primaryKeyValue]` | Primary Key value of Row                                                                                      |             ✅             |     ❌      |
| `[timestamp]`       | Timestamp when Alert triggered                                                                                |             ✅             |     ✅      |
| `[trigger]`         | What caused Alert to fire                                                                                     |             ✅             |     ✅      |
| `[numberOfRows]`    | Count of Rows added or deleted                                                                                |             ❌             |     ✅      |
| `[rowData.x]`       | Changed Row (e.g. `[rowData.price]`)                                                                          |             ✅             |     ❌      |
| `[context.x]`       | Any [AG Grid context](https://www.ag-grid.com/javascript-data-grid/context/) provided (e.g. `[context.name]`) |             ✅             |     ✅      |

- `[trigger]` values that can be returned for [Data Change](https://www.adaptabletools.com/docs/handbook-alerting-data-change/index.md) & [Aggregation](https://www.adaptabletools.com/docs/handbook-alerting-aggregation/index.md) Alerts are: `Edit`, `Tick`, `Undo`, `AggChange`
- `[trigger]` values that can be returned for [Row Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md) are: `Added`, `Edited`, `Deleted`, `Loaded`

**Example: Custom Alert Messages (Templates)**

Providing Custom Alert Message using Template Literals

- This demo shows how to provide a Custom Alert Message using the Alert Definition with **Template Literals**
- We have created 3 Alerts each of which provides a custom Header or Text (or both) using different Template Literal props:
  - A `Warning` [Data Change Alert](https://www.adaptabletools.com/docs/handbook-alerting-data-change/index.md) fires any time a value is changed in the `Language` Column - with templates in both Message Header and Text
  - A `Success` [Row Change Alert](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md) fires when a new Row is added (can by triggered by "Add Python" button in Dashboard) - with template in Message Text
  - An `Info` [Aggregation Alert](https://www.adaptabletools.com/docs/handbook-alerting-aggregation/index.md) fires when the lowest row in the `Github Watchers` column is less than 50 - with template in Message Header

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
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 {
  AdaptableButton,
  AdaptableOptions,
  DashboardButtonContext,
  DataUpdateConfig,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export default function createPython(): WebFramework {
  return {
    id: Math.floor(Math.random() * (1000000 - 5000 + 1) + 200000),
    name: 'python',
    description: 'A very popular language.',
    created_at: new Date().toDateString(),
    updated_at: new Date().toDateString(),
    pushed_at: new Date().toDateString(),
    github_stars: 5000,
    language: 'Python',
    open_issues_count: 750,
    license: 'MIT License',
    github_watchers: 6671,
    topics: ['duck typing', 'proxies', 'prerformance', 'solid'],
    has_projects: true,
    has_wiki: true,
    has_pages: false,
    closed_issues_count: 12326,
    open_pr_count: 749,
    closed_pr_count: 1708,
    week_issue_change: 15,
  };
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Alert Message - Templates',
  notificationsOptions: {
    duration: 'always',
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Add Python Row',
        buttonStyle: {
          tone: 'neutral',
          variant: 'outlined',
        },
        onClick: (
          _button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const python: WebFramework = createPython();
          const dataUpdateConfig: DataUpdateConfig = {
            runAsync: true,
            addIndex: 0,
          };
          context.adaptableApi.gridApi.addGridData([python], dataUpdateConfig);
        },
      },
    ],
  },

  initialState: {
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-language',
          MessageType: 'Warning',
          Scope: {
            ColumnIds: ['language'],
          },
          Rule: 'ANY_CHANGE()',
          MessageHeader: '[column] Column Changed!',
          MessageText:
            'Value changed from [oldValue] to [newValue] in row where framework is "[rowData.name]" (Primary Key: [primaryKeyValue])',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
        {
          Name: 'alert-row-added',
          Rule: 'ROW_ADDED{}',
          MessageType: 'Success',
          MessageHeader: 'You added a row',
          MessageText: '[numberOfRows] Rows were [trigger]',
          Scope: {
            All: true,
          },
          AlertProperties: {
            DisplayNotification: true,
            HighlightRow: {
              BackColor: 'var(--ab-color-palette-28)',
              ForeColor: 'var(--ab-color-palette-14)',
            },
          },
        },
        {
          Name: 'alert-github-watchers',
          MessageType: 'Info',
          Scope: {
            All: true,
          },
          MessageHeader: '[trigger] Alert activated ',
          Rule: 'MIN{[github_watchers]} < 50',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

### Alert Options

Alert Definition Template Literals are sufficient to meet most use cases where a different Message is required to appear each time the Alert is triggered.

However if greater custom flexibility is required, developers can create a completely dynamic Message with any text - via 2 function properties in [Alert Options](https://www.adaptabletools.com/docs/technical-reference-alerting/index.md):

Both functions receive Context describing the Change that triggered the Alert (and associated Alert Definition)

- `alertMessageHeader` - allows developers to provide a custom message **header** 
- `alertMessageText` - allows developers to provide custom message **text** 

### `alertMessageHeader`

Function providing a Header to display for an Alert

By default the header displayed in an Alert is provided by the `MessageHeader` property in the Alert Definition.

If that is not provided, AdapTable will provide the Message dynamically based on the Alert Rule and Cell Change.

However the highest priority is given to this property - a function to be invoked by AdapTable when the Alert fires.

The function receives an [`Alert Message Context`](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md) object (which includes an Alert Definition and Cell and Grid Data Change information) and returns a string:

```ts
alertMessageHeader?: (alertMessageContext: AlertMessageContext) => string | undefined;
```

The full definition of the Alert Message Context is as follows:

| Property | Type | Description |
| --- | --- | --- |
| [alertDefinition](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#alertdefinition) | [`AlertDefinition`](https://www.adaptabletools.com/docs/reference/alertdefinition.md) | Current Alert Definition |
| [cellDataChangedInfo](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#celldatachangedinfo) | [`CellDataChangedInfo`](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md)`<TData>` | Cell Data change that might have triggered the Alert |
| [rowDataChangedInfo](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#rowdatachangedinfo) | [`RowDataChangedInfo`](https://www.adaptabletools.com/docs/reference/rowdatachangedinfo.md)`<TData>` | Row Data change that might have triggered the Alert (e.g. Row Added or Removed) |

```ts {4}
// Set a custom Alert Header for when the changed Column is Github Stars
const adaptableOptions: AdaptableOptions = {
   alertOptions: {
        alertMessageHeader: (alertMessageContext: AlertMessageContext) => {
            if(alertMessageContext.cellDataChangedInfo.column.columnId=='github_stars'){
                return 'Changed Stars!'
            }
        }
    },
} 
```

### `alertMessageText`

Function providing a Message to display in an Alert

By default the message displayed in an Alert is provided by the `MessageText` property in the Alert Definition.

If that is not provided, AdapTable will provide the Message dynamically based on the Alert Rule and Cell Change.

However the highest priority is given to this property - a function to be invoked by AdapTable when the Alert fires.

The function receives an [`Alert Message Context`](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md) object (which includes an Alert Definition and Cell and Grid Data Change information) and returns a string:

```ts
alertMessageText?: (alertMessageContext: AlertMessageContext) => string | undefined;
```

The full definition of the Alert Message Context is as follows:

| Property | Type | Description |
| --- | --- | --- |
| [alertDefinition](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#alertdefinition) | [`AlertDefinition`](https://www.adaptabletools.com/docs/reference/alertdefinition.md) | Current Alert Definition |
| [cellDataChangedInfo](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#celldatachangedinfo) | [`CellDataChangedInfo`](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md)`<TData>` | Cell Data change that might have triggered the Alert |
| [rowDataChangedInfo](https://www.adaptabletools.com/docs/reference/alertmessagecontext.md#rowdatachangedinfo) | [`RowDataChangedInfo`](https://www.adaptabletools.com/docs/reference/rowdatachangedinfo.md)`<TData>` | Row Data change that might have triggered the Alert (e.g. Row Added or Removed) |

```ts {4}
// Set a custom Alert Message for when the changed Column is Github Stars
const adaptableOptions: AdaptableOptions = {
   alertOptions: {
        alertMessageText: (alertMessageContext: AlertMessageContext) => {
            if(alertMessageContext.cellDataChangedInfo.column.columnId=='github_stars'){
                return 'The stars have changed!'
            }
        }
    },
} 
```

- These 2 properties are only available for Alerts created at Design-Time and cannot be set in the UI
- This is because Alert State is saved as JSON which needs to be stringified (and cannot include functions)

**Example: Custom Alert Messages (Options)**

Providing Custom Alert Message via Alert Options

- This demo shows how to provide a Custom Message Header and Text via Alert Options - so that they are diferent each time the Alert fires:
- An `Info` Alert fires when any value is changed in the `Github Stars` column
- The Custom Header references the RowData to get the Framework in the row where the change was made
- The Custom Text references the new value that has been given to the Cell which triggered the Alert
### Expand to see the Custom Header and Text Messages provided

The Alert Definition contains the basic Alert Definition:
```ts
Alert: {
  AlertDefinitions: [
    {
      Name: 'alert-any',
      MessageType: 'Info',
      Scope: {
        ColumnIds: ['github_stars'],
      },
      Rule: 'ANY_CHANGE()',
      AlertProperties: {
        DisplayNotification: true,
      },
    },
  ],
},
```
In Alert Options we provide Custom Message Header and Text if the change occurred in the Github Stars column
Note: we have to return undefined if it is not a match so we can "fall through" to the other options
```ts
alertOptions: {
  alertMessageHeader: (alertMessageContext: AlertMessageContext) => {
    return alertMessageContext.cellDataChangedInfo?.column.columnId == 'github_stars' ?
     'Stars changed for: ' + alertMessageContext.cellDataChangedInfo?.rowData['name']
      : undefined;
  },
  alertMessageText: (alertMessageContext: AlertMessageContext) => {
    return alertMessageContext.cellDataChangedInfo?.column.columnId == 'github_stars' ?
     'New value for Github Stars is: ' + alertMessageContext?.cellDataChangedInfo?.newValue
      : undefined;
  },
},
```

- Edit a cell in the `Github Stars` Column and see the Alert with the custom Header and Text messages
- Note the Alert Message is different for eaach row in the Grid

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
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, AlertMessageContext} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Alert Message - Options',
  alertOptions: {
    alertMessageHeader: (alertMessageContext: AlertMessageContext) => {
      return alertMessageContext.cellDataChangedInfo?.column.columnId ==
        'github_stars'
        ? 'Stars changed for: ' +
            alertMessageContext.cellDataChangedInfo?.rowData['name']
        : undefined;
    },
    alertMessageText: (alertMessageContext: AlertMessageContext) => {
      return alertMessageContext.cellDataChangedInfo?.column.columnId ==
        'github_stars'
        ? 'New value for Github Stars is: ' +
            alertMessageContext?.cellDataChangedInfo?.newValue
        : undefined;
    },
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-github-stars',
          MessageType: 'Info',
          Scope: {
            ColumnIds: ['github_stars'],
          },
          Rule: 'ANY_CHANGE()',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```
