# Configuring Comments

Canonical page: https://www.adaptabletools.com/docs/handbook-comments-configuring

- Developers can configure which Cells in the Grid are able to receive Comments
- Comments open on hover by default, or via the Context Menu (`showCommentAction`)
- And like everything in AdapTable, Comments can be easily themed using CSS Variables

Comments are not available until you provide both load and persist functions in `commentOptions` on [Adaptable Options](https://www.adaptabletools.com/docs/technical-reference-adaptable-options/index.md).

Comments use a very similar loading and persisting pattern as [Team Sharing](https://www.adaptabletools.com/docs/handbook-team-sharing-configuring/index.md)

[`CommentOptions`](https://www.adaptabletools.com/docs/reference/commentoptions.md) defines **six** properties:

| Property | Required | Section |
| -------- | -------- | ------- |
| `loadCommentThreads` | Yes | Setting up Comments |
| `persistCommentThreads` | Yes | Setting up Comments |
| `isCellCommentable` | No | Commentable Cells |
| `dateFormat` | No | Timestamp Date Format |
| `showCommentAction` | No | Viewing Comments |
| `showPopupCloseButton` | No | Viewing Comments |

### Setting up Comments

There are 2 steps you **must** follow in order for Comments to be available to end users:

Supply async `loadCommentThreads` in [Comment Options](https://www.adaptabletools.com/docs/technical-reference-comments/index.md).

It receives [`CommentLoadContext`](https://www.adaptabletools.com/docs/reference/commentloadcontext.md) and returns saved [`CommentThread`](https://www.adaptabletools.com/docs/reference/commentthread.md) objects from your store.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  commentOptions: {
    loadCommentThreads: async (context: CommentLoadContext) => {
      commentsService.subscribeToComments(comments => {
        context.adaptableApi.commentApi.setComments(comments);
      });
      return commentsService.getComments();
    },
  },
};
```

Supply async `persistCommentThreads` in [Comment Options](https://www.adaptabletools.com/docs/technical-reference-comments/index.md).

AdapTable calls it with the **full** thread list after a comment is added, edited, or deleted.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  commentOptions: {
    persistCommentThreads: async (commentThreads: CommentThread[]) => {
      commentsService.setComments(commentThreads);
    },
  },
};
```

The Comment module follows the same [Entitlements](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) as other modules (`defaultAccessLevel` is `Full`). If you have set `defaultAccessLevel` to `Hidden`, grant Comment `Full` or `ReadOnly` or the UI will stay hidden even after load and persist are wired up.

## Commentable Cells

By default all cells in AG Grid - even readonly ones - can receive a Comment.

### `isCellCommentable`

Function enabling specific Cells to be excluded from Comments

The function receives a [`CommentableCellContext`](https://www.adaptabletools.com/docs/reference/commentablecellcontext.md) (including the `gridCell`) and returns whether that Cell can show Comments.

```ts {3-11}
commentOptions: {
  isCellCommentable: (context: CommentableCellContext) => {
    // Don't allow Comments on the language column or rows where license is 'Other'
    if (
      context.gridCell.column.columnId === 'language' ||
      context.gridCell.rowNode.data['license'] === 'Other'
    ) {
      return false;
    }
    return true;
  },
},
```

**Example: Configuring Commentable Cells**

Setting which Cells can display Comments

- `isCellCommentable` in `adaptableOptions.ts` blocks Comments when:
  - the cell is in the `language` column
  - the row’s `license` value is `Other`

- Right-click a cell in `name` — *Add Comment* is available
- Right-click a cell in `language`, or any cell in a row whose `license` is `Other` — *Add Comment* is not offered

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 {
  CommentableCellContext,
  CommentLoadContext,
  CommentThread,
  CustomContextMenuContext,
  AdaptableOptions,
  AdaptableSystemContextMenuItem,
  AdaptableContextMenuItemName,
} from '@adaptabletools/adaptable';

import {WebFramework} from './rowData';

const COMMENTS_PERSISTENCE_KEY = 'docs-commentable-cell-comments';

export class CommentsService {
  channel = new BroadcastChannel('comments');

  constructor() {}

  subscribeToComments(callback: (comments: CommentThread[]) => void) {
    console.log('subscribing to comments');
    this.channel.onmessage = event => {
      callback(event.data);
    };
  }

  setComments(comments: CommentThread[]) {
    console.log('sending comments', comments);
    localStorage.setItem(COMMENTS_PERSISTENCE_KEY, JSON.stringify(comments));
    this.channel.postMessage(comments);
  }

  getComments(): CommentThread[] {
    console.log('getting comments');
    const commentsString = localStorage.getItem(COMMENTS_PERSISTENCE_KEY);
    return commentsString ? JSON.parse(commentsString) : [];
  }
}

const commentsService = new CommentsService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Commentable Cells',
  userName: 'Demo User',
  contextMenuOptions: {
    customContextMenu: (customMenuContext: CustomContextMenuContext) => {
      if (
        customMenuContext.gridCell.column.columnId === 'language' ||
        customMenuContext.gridCell.rowNode.data['license'] === 'Other'
      ) {
        return customMenuContext.defaultAdaptableMenuStructure;
      }

      return customMenuContext.defaultAdaptableMenuStructure
        .filter(
          (
            item
          ): item is AdaptableSystemContextMenuItem<AdaptableContextMenuItemName> =>
            item !== '-'
        )
        .filter(item => item.category === 'Comment');
    },
  },
  commentOptions: {
    loadCommentThreads: async (commentLoadContext: CommentLoadContext) => {
      commentsService.subscribeToComments(comments => {
        commentLoadContext.adaptableApi.commentApi.setComments(comments);
      });
      return commentsService.getComments();
    },
    persistCommentThreads: async (commentThreads: CommentThread[]) => {
      commentsService.setComments(commentThreads);
    },
    isCellCommentable: (context: CommentableCellContext) => {
      // Dont allow Comments on the Language Column or Rows where License is 'Other'
      if (
        context.gridCell.column.columnId === 'language' ||
        context.gridCell.rowNode.data['license'] === 'Other'
      ) {
        return false;
      }
      return true;
    },
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_, context) => {
          localStorage.removeItem(COMMENTS_PERSISTENCE_KEY);
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Comment'],
    },
    Theme: {CurrentTheme: 'dark'},

    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'github_stars',
            'license',
            'github_watchers',
            'language',
            'open_issues_count',
            'closed_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'description',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

## Theming Comments

By default the triangle in a cell to denote a Comment is painted blue.

Technically AdapTable uses the value of the `--ab-color-info` variable, which itself can be overridden

However, like everything [theming-related](https://www.adaptabletools.com/docs/handbook-theming/index.md) in AdapTable, this can be overridden using [CSS Variables](https://www.adaptabletools.com/docs/handbook-theming-custom/index.md).

All that is required is to provide a different value for the `--ab-CellComment-triangle-color` CSS variable.

**Example: Comments CSS**

Configuring Comments using CSS variables

- `styles.css` sets `--ab-CellComment-triangle-color` so the comment triangle appears yellow

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
  rowData.ts           [template]
  styles.css           [template + shown below]
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 {
  AdaptableContextMenuItemName,
  AdaptableSystemContextMenuItem,
  CommentLoadContext,
  CommentThread,
  CustomContextMenuContext,
} from '@adaptabletools/adaptable';
import {AdaptableOptions} from '@adaptabletools/adaptable';

import {WebFramework} from './rowData';

const COMMENTS_PERSISTENCE_KEY = 'adaptable-css-comments';

export class CommentsService {
  channel = new BroadcastChannel('comments');

  constructor() {}

  subscribeToComments(callback: (comments: CommentThread[]) => void) {
    console.log('subscribing to comments');
    this.channel.onmessage = event => {
      callback(event.data);
    };
  }

  setComments(comments: CommentThread[]) {
    console.log('sending comments', comments);
    localStorage.setItem(COMMENTS_PERSISTENCE_KEY, JSON.stringify(comments));
    this.channel.postMessage(comments);
  }

  getComments(): CommentThread[] {
    console.log('getting comments');
    const commentsString = localStorage.getItem(COMMENTS_PERSISTENCE_KEY);
    return commentsString ? JSON.parse(commentsString) : [];
  }
}
const commentsService = new CommentsService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Comments CSS',
  userName: 'Demo User',
  contextMenuOptions: {
    customContextMenu: (customMenuContext: CustomContextMenuContext) => {
      return customMenuContext.defaultAdaptableMenuStructure
        .filter(
          (
            item
          ): item is AdaptableSystemContextMenuItem<AdaptableContextMenuItemName> =>
            item !== '-'
        )
        .filter(
          item => item.category === 'Comment' || item.category === 'Note'
        );
    },
  },
  commentOptions: {
    loadCommentThreads: async (commentLoadContext: CommentLoadContext) => {
      commentsService.subscribeToComments(comments => {
        commentLoadContext.adaptableApi.commentApi.setComments(comments);
      });
      return commentsService.getComments();
    },
    persistCommentThreads: async (commentThreads: CommentThread[]) => {
      commentsService.setComments(commentThreads);
    },
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_, context) => {
          localStorage.removeItem(COMMENTS_PERSISTENCE_KEY);
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Comment'],
    },
    Theme: {CurrentTheme: 'dark'},

    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'github_stars',
            'license',
            'github_watchers',
            'language',
            'open_issues_count',
            'closed_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'description',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = (adaptableReadyInfo: AdaptableReadyInfo) => {
  adaptableReadyInfo.adaptableApi.commentApi.clearComments();
  setTimeout(() => {
    adaptableReadyInfo.adaptableApi.commentApi.addComment(
      'Does anyone know this Stencil license?',
      {
        ColumnId: 'license',
        PrimaryKeyValue: 82095231,
      }
    );
    adaptableReadyInfo.adaptableApi.commentApi.addComment(
      'Does anyone know this Polymer license?',
      {
        ColumnId: 'license',
        PrimaryKeyValue: 5532320,
      }
    );
  }, 100);
};
```

**`src/styles.css`**

```css
/*  Custom Variables */

/* Overriding the dark theme */
:root.ab--theme-dark {
  --ab-CellComment-triangle-color: yellow;
}
```

## Timestamp Date Format

AdapTable provides a property to configure how the timestamp of a Comment is displayed.

This is used in both the Comment itself and the Comments screen that shows all current Comments

### `dateFormat`

Date Format to use for timestamp in Comments

By default AdapTable will format the timestamp using `dd-MM-yyyy HH:mm:ss`.

Use this property to set an alternative Date Format, including via a function if preferred.

```ts {3}
const adaptableOptions: AdaptableOptions = {
  commentOptions: {
    dateFormat: 'MMM do yyyy',
  },
};
```

**Example: Comments Date Format**

Configuring the format for Comments timestamp

- `dateFormat: 'MMM do yyyy'` in `adaptableOptions.ts` for Comment timestamps

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
  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 {
  CommentableCellContext,
  CommentLoadContext,
  CommentThread,
  CustomContextMenuContext,
  AdaptableOptions,
  AdaptableSystemContextMenuItem,
  AdaptableContextMenuItemName,
} from '@adaptabletools/adaptable';

import {WebFramework} from './rowData';

const COMMENTS_PERSISTENCE_KEY = 'docs-commentable-cell-comments';

export class CommentsService {
  channel = new BroadcastChannel('comments');

  constructor() {}

  subscribeToComments(callback: (comments: CommentThread[]) => void) {
    console.log('subscribing to comments');
    this.channel.onmessage = event => {
      callback(event.data);
    };
  }

  setComments(comments: CommentThread[]) {
    console.log('sending comments', comments);
    localStorage.setItem(COMMENTS_PERSISTENCE_KEY, JSON.stringify(comments));
    this.channel.postMessage(comments);
  }

  getComments(): CommentThread[] {
    console.log('getting comments');
    const commentsString = localStorage.getItem(COMMENTS_PERSISTENCE_KEY);
    return commentsString ? JSON.parse(commentsString) : [];
  }
}

const commentsService = new CommentsService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Comments Date Format',
  userName: 'Demo User',
  contextMenuOptions: {
    customContextMenu: (customMenuContext: CustomContextMenuContext) => {
      return customMenuContext.defaultAdaptableMenuStructure
        .filter(
          (
            item
          ): item is AdaptableSystemContextMenuItem<AdaptableContextMenuItemName> =>
            item !== '-'
        )
        .filter(
          item => item.category === 'Comment' || item.category === 'Note'
        );
    },
  },
  commentOptions: {
    loadCommentThreads: async (commentLoadContext: CommentLoadContext) => {
      commentsService.subscribeToComments(comments => {
        commentLoadContext.adaptableApi.commentApi.setComments(comments);
      });
      return commentsService.getComments();
    },
    persistCommentThreads: async (commentThreads: CommentThread[]) => {
      commentsService.setComments(commentThreads);
    },
    dateFormat: 'MMM do yyyy',
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_, context) => {
          localStorage.removeItem(COMMENTS_PERSISTENCE_KEY);
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Comment'],
    },
    Theme: {CurrentTheme: 'dark'},

    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'github_stars',
            'license',
            'github_watchers',
            'language',
            'open_issues_count',
            'closed_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'description',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = (adaptableReadyInfo: AdaptableReadyInfo) => {
  adaptableReadyInfo.adaptableApi.commentApi.clearComments();
  setTimeout(() => {
    adaptableReadyInfo.adaptableApi.commentApi.addComment(
      'Does anyone know this Stencil license?',
      {
        ColumnId: 'license',
        PrimaryKeyValue: 82095231,
      }
    );
    adaptableReadyInfo.adaptableApi.commentApi.addComment(
      'Does anyone know this Polymer license?',
      {
        ColumnId: 'license',
        PrimaryKeyValue: 5532320,
      }
    );
  }, 100);
};
```

## Viewing Comments

By default run-time users see a Comment when the mouse hovers over a cell that contains one.

Set `showCommentAction` in [Comment Options](https://www.adaptabletools.com/docs/technical-reference-comments/index.md) to `'menu'` to turn off hover and open the thread from the [Context Menu](https://www.adaptabletools.com/docs/ui-context-menu/index.md) instead (*Show Comment*).

Use `showPopupCloseButton` (default `true`) to show or hide the Close button on the Comments popup.

### `showCommentAction`

Whether Comments open on hover or via the Context Menu

```ts {3}
  commentOptions: {
    showCommentAction: 'menu',
  },
```

**Example: Comments Menu**

Viewing Comments via Context Menu

- `showCommentAction: 'menu'` in `adaptableOptions.ts` — hovering a commented cell does nothing
- Right-click the cell and choose *Show Comment* to open the thread

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 {
  AdaptableContextMenuItemName,
  AdaptableSystemContextMenuItem,
  CommentLoadContext,
  CommentThread,
  CustomContextMenuContext,
} from '@adaptabletools/adaptable';
import {AdaptableOptions} from '@adaptabletools/adaptable';

import {WebFramework} from './rowData';

const COMMENTS_PERSISTENCE_KEY = 'adaptable-css-comments';

export class CommentsService {
  channel = new BroadcastChannel('comments');

  constructor() {}

  subscribeToComments(callback: (comments: CommentThread[]) => void) {
    console.log('subscribing to comments');
    this.channel.onmessage = event => {
      callback(event.data);
    };
  }

  setComments(comments: CommentThread[]) {
    console.log('sending comments', comments);
    localStorage.setItem(COMMENTS_PERSISTENCE_KEY, JSON.stringify(comments));
    this.channel.postMessage(comments);
  }

  getComments(): CommentThread[] {
    console.log('getting comments');
    const commentsString = localStorage.getItem(COMMENTS_PERSISTENCE_KEY);
    return commentsString ? JSON.parse(commentsString) : [];
  }
}
const commentsService = new CommentsService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Viewing Comments via Context Menu',
  userName: 'Demo User',

  commentOptions: {
    showCommentAction: 'menu',
    loadCommentThreads: async (commentLoadContext: CommentLoadContext) => {
      commentsService.subscribeToComments(comments => {
        commentLoadContext.adaptableApi.commentApi.setComments(comments);
      });
      return commentsService.getComments();
    },
    persistCommentThreads: async (commentThreads: CommentThread[]) => {
      commentsService.setComments(commentThreads);
    },
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_, context) => {
          localStorage.removeItem(COMMENTS_PERSISTENCE_KEY);
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Comment'],
    },
    Theme: {CurrentTheme: 'dark'},

    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'github_stars',
            'license',
            'github_watchers',
            'language',
            'open_issues_count',
            'closed_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'description',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

### `showPopupCloseButton`

Show a Close Button on the Comments popup

The Comments popup is AdapTable UI. Set this to `false` if you do not want the Close Button.

```ts {3}
  commentOptions: {
    showPopupCloseButton: false,
  },
```
