# Sharing Comments

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

- Comments are cell-level annotations designed with collaboration in mind
- Users can see each other's Comments and add to the Comment Thread
- The Comment Thread is persisted (via developer provided functions) so that all users can access them

Comments are **annotations** that are attached to individual **Cells** in AG Grid.

They are stored remotely, rather than with the Grid’s underlying data source, and are designed with collaboration in mind.

The Comment popup, cell triangle and menus are **AdapTable UI**. Unlike [Notes](https://www.adaptabletools.com/docs/handbook-notes/index.md) (which wrap AG Grid Cell Notes), Comments do not require an AG Grid module.

- Comments differ from [Notes](https://www.adaptabletools.com/docs/handbook-notes/index.md) — Comments enable colleague communication; Notes are personal
- Comments differ from [Free Text Columns](https://www.adaptabletools.com/docs/handbook-freetext-column/index.md) — Comments are **cell-level threads**; Free Text is **column-shaped** state (one value per row), not collaborative annotations

Multiple users can add Comments to the same Comment Thread, and all the Comments are visible to all users.

Comments are **not** available if you are using an [auto-generated Primary Key](https://www.adaptabletools.com/docs/getting-started-primary-key/index.md#auto-generated-key)

**Example: Comments in AdapTable**

Using Comments

- Simulate two users — **Alice** and **Bob** — via the pinned user toolbar (see `adaptableOptions.ts` and the framework-specific app file)
- Each user sees the other’s Comments (localStorage + `BroadcastChannel`); only the author can edit or delete their own Comment

- Switch between Alice and Bob, add Comments on the same cell, and confirm both users see the thread
- Try editing a Comment written by the other user — it should not be editable

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

const COMMENTS_PERSISTENCE_KEY = 'docs-demo-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) : [];
  }

  clearComments() {
    console.log('clearing comments');
    localStorage.setItem(COMMENTS_PERSISTENCE_KEY, JSON.stringify([]));
    this.channel.postMessage([]);
  }
}

const commentsService = new CommentsService();

export const getAdaptableOptionsForUser = (
  userName: 'Alice' | 'Bob',
  updateCurrentUser: (userName: 'Alice' | 'Bob') => void
): AdaptableOptions<WebFramework> => {
  const commonInitialState: InitialState = {
    Dashboard: {
      ModuleButtons: ['Comment'],
      PinnedToolbars: ['CurrentUser'],
    },
    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,
        },
      ],
    },
  };
  const userSpecificInitialState =
    userName === 'Alice'
      ? {
          Theme: {
            CurrentTheme: 'light',
          },
        }
      : // Bob
        {
          Theme: {
            CurrentTheme: 'dark',
          },
        };

  const adaptableOptions: AdaptableOptions<WebFramework> = {
    primaryKey: 'id',
    adaptableId: 'Comments',
    adaptableStateKey: `DocsCommentsDemo_${userName}`,
    userName: userName,
    contextMenuOptions: {
      customContextMenu: (customMenuContext: CustomContextMenuContext) => {
        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);
      },
    },
    dashboardOptions: {
      customToolbars: [
        {
          name: 'CurrentUser',
          title: 'Current User',
          toolbarButtons: [
            {
              label: 'Alice',
              buttonStyle: () => {
                return {
                  tone: userName === 'Alice' ? 'success' : 'neutral',
                  variant: userName === 'Alice' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Alice');
              },
            },
            {
              label: 'Bob',
              buttonStyle: () => {
                return {
                  tone: userName === 'Bob' ? 'success' : 'neutral',
                  variant: userName === 'Bob' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Bob');
              },
            },
          ],
        },
      ],
      customDashboardButtons: [
        {
          tooltip: 'Reset state',
          icon: {
            name: 'refresh',
          },
          buttonStyle: {
            tone: 'error',
          },
          onClick: (_, context) => {
            localStorage.removeItem(COMMENTS_PERSISTENCE_KEY);
            ['Alice', 'Bob'].forEach(user => {
              localStorage.removeItem(`DocsCommentsDemo_${user}`);
            });
            context.adaptableApi.stateApi.reloadInitialState();
          },
        },
      ],
    },
    initialState: {
      ...commonInitialState,
      ...userSpecificInitialState,
    },
  };

  return adaptableOptions;
};
```

**`src/index.ts`**

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

import '@adaptabletools/adaptable/index.css';

import './styles.css';

import {gridOptions} from './gridOptions';
import {onAdaptableReady} from './onAdaptableReady';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';

let currentAdaptableInstance: AdaptableApi | undefined;

let currentUser: 'Alice' | 'Bob' = 'Alice';

function updateCurrentUser(userName: 'Alice' | 'Bob') {
  currentUser = userName;
  initializeAdaptable(currentUser);
}

async function initializeAdaptable(userName: 'Alice' | 'Bob') {
  // destroy the previous instance (if existing)
  if (currentAdaptableInstance) {
    const config: any = {
      unmount: true,
      destroyApi: true,
    };
    currentAdaptableInstance.destroy(config);
  }

  currentAdaptableInstance = await Adaptable.init(
    {
      ...getAdaptableOptionsForUser(userName, updateCurrentUser),
    } as AdaptableOptions<WebFramework>,
    {gridOptions: {...gridOptions}, modules: agGridModules}
  );
  currentAdaptableInstance.eventApi.on(
    'AdaptableReady',
    (readyInfo: AdaptableReadyInfo) => {
      onAdaptableReady(readyInfo);
    }
  );
}

initializeAdaptable(currentUser);
```

**`src/App.tsx`** (React version)

```ts
import * as React from 'react';
import {useState} from 'react';
import {
  Adaptable,
  AdaptableApi,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable-react-aggrid';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = ({
  currentUser,
  onCurrentUserChange,
}: {
  currentUser: 'Alice' | 'Bob';
  onCurrentUserChange: (userName: 'Alice' | 'Bob') => void;
}) => {
  const adaptableApiRef = React.useRef<AdaptableApi>(null);

  const adaptableOptions = getAdaptableOptionsForUser(
    currentUser,
    onCurrentUserChange
  );

  const agGridOptions = {...gridOptions};
  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <Adaptable.Provider
        gridOptions={agGridOptions}
        adaptableOptions={adaptableOptions}
        modules={[...agGridModules]}
        onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
          // save a reference to adaptable api
          adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
          onAdaptableReady(adaptableReadyInfo);
        }}>
        <Adaptable.UI key={`${currentUser}-ui`} style={{flex: 'none'}} />
        <Adaptable.AgGridReact />
      </Adaptable.Provider>
    </div>
  );
};

const App: React.FunctionComponent = () => {
  const [currentUser, setCurrentUser] = useState<'Alice' | 'Bob'>('Alice');

  return (
    <Grid
      key={currentUser}
      currentUser={currentUser}
      onCurrentUserChange={userName => setCurrentUser(userName)}
    />
  );
};
export default App;
```

**`src/app/app.component.ts`** (Angular version)

```ts
import {ChangeDetectorRef, Component, Inject} from '@angular/core';

import {AdaptableReadyInfo, AdaptableOptions} from '@adaptabletools/adaptable-angular-aggrid';
import {GridOptions} from 'ag-grid-enterprise';

// Adaptable styles
import '@adaptabletools/adaptable-angular-aggrid/index.css';

// AG Grid styles

import './styles.css';

// grid configuration
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {onAdaptableReady} from './onAdaptableReady';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';

@Component({
  standalone: false,
  selector: 'app-root',
  template: `
    <div id="demoOutputAbove"></div>
    <adaptable-provider
      *ngIf="isUpToDate"
      [adaptableOptions]="adaptableOpts"
      [gridOptions]="agGridOptions"
      [modules]="modules"
      (adaptableReady)="adaptableReady($event)"
      style="height: 100vh; width: 100vw;">
      <adaptable-ui style="flex: none"></adaptable-ui>
      <ag-grid-angular
        *adaptable="let adaptable"
        [gridOptions]="adaptable.gridOptions"
        [modules]="adaptable.modules"
        style="flex: 1">
      </ag-grid-angular>
    </adaptable-provider>
    <div id="demoOutputBelow"></div>
  `,
  styles: [
    `
      :host {
        height: 100vh;
        display: flex;
        flex-flow: column;
      }
    `,
  ],
})
export class AppComponent {
  adaptableOpts: AdaptableOptions<WebFramework>;
  agGridOptions: GridOptions<WebFramework>;
  modules = agGridModules;

  currentUser: 'Alice' | 'Bob';
  isUpToDate = true;

  constructor(
    @Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef
  ) {
    this.currentUser = 'Alice';
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  setCurrentUser(currentUser: 'Alice' | 'Bob') {
    this.isUpToDate = false;
    this.changeDetectorRef.detectChanges();

    this.currentUser = currentUser;
    this.initializeAdaptable();
    this.isUpToDate = true;
    this.changeDetectorRef.detectChanges();
  }

  initializeAdaptable() {
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  adaptableReady($event: AdaptableReadyInfo) {
    onAdaptableReady($event);
  }
}
```

**`src/App.vue`** (Vue version)

```ts
<template>
  <Grid :currentUser="currentUser" @currentUserChange="setCurrentUser" />
</template>

<script lang="ts">
import {ref, defineComponent} from 'vue';
import {
  AdaptableProvider,
  AdaptableAgGridVue,
  AdaptableUI,
} from '@adaptabletools/adaptable-vue3-aggrid';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = defineComponent({
  props: {
    currentUser: {
      type: String,
      required: true,
    },
  },
  emits: ['currentUserChange'],
  setup(props, {emit}) {
    const adaptableOptions = getAdaptableOptionsForUser(
      props.currentUser,
      userName => emit('currentUserChange', userName)
    );

    const agGridOptions = {...gridOptions};

    return {
      adaptableOptions,
      agGridOptions,
      agGridModules,
      onAdaptableReady,
    };
  },
  components: {
    AdaptableProvider,
    AdaptableAgGridVue,
    AdaptableUI,
  },
  template: `
    <AdaptableProvider
        :gridOptions="agGridOptions"
        :adaptableOptions="adaptableOptions"
        :modules="agGridModules"
        @onAdaptableReady="onAdaptableReady">
      <div style="display: flex; flex-direction: column; height: 100vh">
        <AdaptableUI :key="currentUser + '-ui'" style="flex: none" />
        <AdaptableAgGridVue style="flex: 1"  />
      </div>
    </AdaptableProvider>
  `,
});

export default defineComponent({
  name: 'App',
  components: {
    Grid,
  },
  setup() {
    const currentUser = ref('Alice');

    const setCurrentUser = userName => {
      currentUser.value = userName;
    };

    return {
      currentUser,
      setCurrentUser,
    };
  },
});
</script>
```

## Comment Threads

Comments are designed to be written at run-time, and to be used in a collaborative manner.

This is achieved by creating a **Comment Thread** for each cell that contains a Comment, to which all permissioned Team Members can contribute.

### Comment Thread Workflow

The steps to create and collaborate on a Comment Thread are as follows:

If Comments are enabled, every cell will include an *Add Comment* [Context Menu Item](https://www.adaptabletools.com/docs/ui-context-menu/index.md).

Use the `isCellCommentable` property in [Comment Options](https://www.adaptabletools.com/docs/technical-reference-comments/index.md) to [configure which cells can show Comments](https://www.adaptabletools.com/docs/handbook-comments-configuring/index.md)

Run-time users can write a new Comment by right-clicking on the desired cell, selecting *Add Comment* from the [Context Menu](https://www.adaptabletools.com/docs/ui-context-menu/index.md) and then adding the required text.

This will automatically create a new **Comment Thread** in which the Comment above has been added with the correct User and Timestamp appended.

This Comment Thread will now be available to all members of the Team to add their own Comments.

Only the Author of a Comment can edit or delete it

Other team members can now add their own Comments to the Comment Thread, which will in turn also be viewable to everyone else.

The Comment page in the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md) (and the Comments Dashboard button) displays all the current Comment Threads and all the Comments they contain.

Users can click on any Comment Thread in that page to open the Comment Thread in the Grid.

## UI Entitlements

The UI Entitlements behaviour for Comments is as expected for `Full` and `Hidden` [`Access Levels`](https://www.adaptabletools.com/docs/reference/accesslevel.md).

The `ReadOnly` Entitlement behaviour is that existing Comments - either previously created or provided by other users are visible - but new Comments cannot be added.

### FAQ

**Can I create Comments for personal use?**
You can, but for that use case we recommend [Notes](https://www.adaptabletools.com/docs/handbook-notes/index.md), which are simpler and stored in AdapTable State.
