---
title: "Configuring the Comments plugin with the Mentions plugin"
description: "Information on configuring the Comments plugin with the Mentions plugin."
canonical_url: "https://www.tiny.cloud/docs/tinymce/latest/comments-with-mentions/"
md_url: "https://www.tiny.cloud/docs/tinymce/7/comments-with-mentions/index.md"
version: "7"
last_updated: "2025-08-20T11:11:01Z"
tokens: 10016
---
Important This page documents TinyMCE 7. For new projects, Tiny recommends using the latest, most up-to-date version. [See TinyMCE 8 documentation](../../latest/comments-with-mentions/).
# Configuring the Comments plugin with the Mentions plugin

The Comments plugin can be used with the [Mentions](../mentions/) plugin to allow users to mention other users in comments.

When a user starts typing a mention with the `@` symbol, the mention dropdown will appear. Users can keep typing to narrow the search results, and either click on the desired user or navigate using arrow keys and press enter to add a mention to the comment.

When the comment is saved, mentioned users will appear in the comment text in the same way as they do in the editor.

All mentions are stored in the comment text as plain text, so for the mentions to be displayed correctly, the [Mentions](../mentions/) plugin must be included in the TinyMCE configuration when the comments are displayed.

> **Important:** To add mentions to comments, both the Comments and Mentions plugins must be included in the TinyMCE configuration, and all required options must be set.

## Callback mode interactive example

**Example**

```js
const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';

const user_id = 'james-wilson';
const collaborator_id = 'mia-andersson';

const now = new Date();
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
const anhourago = new Date(now.getTime() - 60 * 60 * 1000).toISOString();
const fakeDelay = 200;

const randomString = () => {
  return crypto.getRandomValues(new Uint32Array(1))[0].toString(36).substring(2, 14);
};

const conversationDb = {
  'mce-conversation_19679600221621399703915': {
    uid: 'mce-conversation_19679600221621399703915',
    comments: [{
      uid: 'mce-conversation_19679600221621399703915',
      author: user_id,
      authorName: 'James Wilson',
      authorAvatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_james-wilson_128_52f19412.jpg',
      content: `What do you think about this? @${collaborator_id}?`,
      createdAt: yesterday,
      modifiedAt: yesterday
    }, {
      uid: 'mce-conversation_19679600221621399703917',
      author: collaborator_id,
      authorName: 'Mia Andersson',
      authorAvatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_mia-andersson_128_e6f9424b.jpg',
      content: `I think this is a great idea @${user_id}!`,
      createdAt: anhourago,
      modifiedAt: anhourago,
    }]
  },
  'mce-conversation_420304606321716900864126': {
    uid: 'mce-conversation_420304606321716900864126',
    comments: [{
      uid: 'mce-conversation_420304606321716900864126',
      author: collaborator_id,
      authorName: 'Mia Andersson',
      authorAvatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_mia-andersson_128_e6f9424b.jpg',
      content: `@${user_id} Please revise this sentence, exclamation points are unprofessional!`,
      createdAt: yesterday,
      modifiedAt: anhourago
    }]
  }
};

const mentions_fetch = async (query, success) => {
  const searchPhrase = query.term.toLowerCase();
  await fetch(`${API_URL}?q=${encodeURIComponent(searchPhrase)}`)
    .then((response) => response.json())
    .then((users) => success(users.data.map((userInfo) => ({
      id: userInfo.id,
      name: userInfo.name,
      image: userInfo.avatar,
      description: userInfo.custom.role
    }))))
    .catch((error) => console.log(error));
};

const mentions_menu_complete = (editor, userInfo) => {
  const span = editor.getDoc().createElement('span');
  span.className = 'mymention';
  span.setAttribute('data-mention-id', userInfo.id);
  span.appendChild(editor.getDoc().createTextNode('@' + userInfo.name));
  return span;
};

const createCard = (userInfo) => {
  const div = document.createElement('div');
  div.innerHTML = (
    '<div class="card">' +
      '<img class="avatar" src="' + userInfo.image + '">' +
      '<h1>' + userInfo.name + '</h1>' +
      '<p>' + userInfo.description + '</p>' +
    '</div>'
  );
  return div;
};

const mentions_select = async (mention, success) => {
  const id = mention.getAttribute('data-mention-id');
  await fetch(`${API_URL}/${id}`)
    .then((response) => response.json())
    .then((userInfo) => {
      const card = createCard({
        id: userInfo.id,
        name: userInfo.name,
        image: userInfo.avatar,
        description: userInfo.custom.role
      });
      success(card);
    })
    .catch((error) => console.error(error));
};

const mentions_menu_hover = async (userInfo, success) => {
  const card = createCard(userInfo);
  success(card);
};

const tinycomments_create = (req, done, fail) => {
    if (req.content === 'fail') {
      fail(new Error('Something has gone wrong...'));
    } else {
      const uid = 'annotation-' + randomString();
      conversationDb[uid] = {
        uid,
        comments: [{
          uid,
          author: user_id,
          authorName: 'James Wilson',
          authorAvatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_james-wilson_128_52f19412.jpg',
          content: req.content,
          createdAt: req.createdAt,
          modifiedAt: req.createdAt
        }]
      };
      setTimeout(() => done({ conversationUid: uid }), fakeDelay);
    }
  };

const tinycomments_reply = (req, done) => {
  const replyUid = 'annotation-' + randomString();
  conversationDb[req.conversationUid].comments.push({
    uid: replyUid,
    author: user_id,
    authorName: 'James Wilson',
    authorAvatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_james-wilson_128_52f19412.jpg',
    content: req.content,
    createdAt: req.createdAt,
    modifiedAt: req.createdAt
  });
  setTimeout(() => done({ commentUid: replyUid }), fakeDelay);
};

const tinycomments_delete = (req, done) => {
  if (user_id === collaborator_id) { // Replace wth your own logic, e.g. check if user created the conversation
    delete conversationDb[req.conversationUid];
    setTimeout(() => done({ canDelete: true }), fakeDelay);
  } else {
    setTimeout(() => done({ canDelete: false, reason: 'Must be admin user' }), fakeDelay);
  }
};

const tinycomments_resolve = (req, done) => {
  const conversation = conversationDb[req.conversationUid];
  if (user_id === conversation.comments[0].author) { // Replace wth your own logic, e.g. check if user has admin priveleges
    delete conversationDb[req.conversationUid];
    setTimeout(() => done({ canResolve: true }), fakeDelay);
  } else {
    setTimeout(() => done({ canResolve: false, reason: 'Must be conversation author' }), fakeDelay);
  }
};

const tinycomments_delete_comment = (req, done) => {
  const oldcomments = conversationDb[req.conversationUid].comments;
  let reason = 'Comment not found';

  const newcomments = oldcomments.filter((comment) => {
    if (comment.uid === req.commentUid) { // Found the comment to delete
      if (user_id === comment.author) { // Replace with your own logic, e.g. check if user has admin privileges
        return false; // Remove the comment
      } else {
        reason = 'Not authorised to delete this comment'; // Update reason
      }
    }
    return true; // Keep the comment
  });

  if (newcomments.length === oldcomments.length) {
    setTimeout(() => done({ canDelete: false, reason }), fakeDelay);
  } else {
    conversationDb[req.conversationUid].comments = newcomments;
    setTimeout(() => done({ canDelete: true }), fakeDelay);
  }
};

const tinycomments_edit_comment = (req, done) => {
  const oldcomments = conversationDb[req.conversationUid].comments;
  let reason = 'Comment not found';
  let canEdit = false;

  const newcomments = oldcomments.map((comment) => {
    if (comment.uid === req.commentUid) { // Found the comment to delete
      if (user_id === comment.author) { // Replace with your own logic, e.g. check if user has admin privileges
        canEdit = true; // User can edit the comment
        return { ...comment, content: req.content, modifiedAt: new Date().toISOString() }; // Update the comment
      } else {
        reason = 'Not authorised to edit this comment'; // Update reason
      }
    }
    return comment; // Keep the comment
  });

  if (canEdit) {
    conversationDb[req.conversationUid].comments = newcomments;
    setTimeout(() => done({ canEdit }), fakeDelay);
  } else {
    setTimeout(() => done({ canEdit, reason }), fakeDelay);
  }
};

const tinycomments_delete_all = (req, done) => {
  const conversation = conversationDb[req.conversationUid];
  if (user_id === conversation.comments[0].author) { // Replace wth your own logic, e.g. check if user has admin priveleges
    delete conversationDb[req.conversationUid];
    setTimeout(() => done({ canDelete: true }), fakeDelay);
  } else {
    setTimeout(() => done({ canDelete: false, reason: 'Must be conversation author' }), fakeDelay);
  }
};

const tinycomments_lookup = (req, done) => {
  setTimeout(() => {
    done({
      conversation: {
        uid: conversationDb[req.conversationUid].uid,
        comments: [...conversationDb[req.conversationUid].comments]
      }
    });
  }, fakeDelay);
};

const tinycomments_fetch = (conversationUids, done) => {
  const fetchedConversations = {};
  conversationUids.forEach((uid) => {
    const conversation = conversationDb[uid];
    if (conversation) {
      fetchedConversations[uid] = {...conversation};
    }
  });
  setTimeout(() => done({ conversations: fetchedConversations }), fakeDelay);
};

const tinycomments_fetch_author_info = (done) => {
  fetch(`${API_URL}/${user_id}`)
    .then(res => res.json())
    .then(currentUser => {
      done({
        author: currentUser.id,
        authorName: currentUser.name,
        authorAvatar: currentUser.avatar
      });
    });
};

tinymce.init({
  selector: 'textarea#comments-callback-with-mentions',
  license_key: 'gpl',
  toolbar: 'addcomment showcomments code | bold italic underline',
  menubar: 'file edit view insert format tools tc help',
  menu: {
    tc: {
      title: 'TinyComments',
      items: 'addcomment showcomments deleteallconversations'
    }
  },
  plugins: [ 'tinycomments', 'mentions', 'help', 'code', 'quickbars', 'link', 'lists', 'image' ],
  quickbars_selection_toolbar: 'alignleft aligncenter alignright | addcomment showcomments',
  quickbars_image_toolbar: 'alignleft aligncenter alignright | rotateleft rotateright | imageoptions',
  
  tinycomments_mode: 'callback',
  tinycomments_mentions_enabled: true,
  sidebar_show: 'showcomments',
  tinycomments_create,
  tinycomments_reply,
  tinycomments_delete,
  tinycomments_resolve,
  tinycomments_delete_all,
  tinycomments_lookup,
  tinycomments_delete_comment,
  tinycomments_edit_comment,
  tinycomments_fetch,
  tinycomments_fetch_author_info,
  mentions_item_type: 'profile',
  mentions_min_chars: 0,
  mentions_selector: '.mymention',
  mentions_fetch,
  mentions_menu_hover,
  mentions_menu_complete,
  mentions_select
});
```

## Embedded mode interactive example

**Example**

```js
const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';

const user_id = 'james-wilson';

const mentions_fetch = async (query, success) => {
  const searchPhrase = query.term.toLowerCase();
  await fetch(`${API_URL}?q=${encodeURIComponent(searchPhrase)}`)
    .then((response) => response.json())
    .then((users) => success(users.data.map((userInfo) => ({
      id: userInfo.id,
      name: userInfo.name,
      image: userInfo.avatar,
      description: userInfo.custom.role
    }))))
    .catch((error) => console.log(error));
};

const mentions_menu_complete = (editor, userInfo) => {
  const span = editor.getDoc().createElement('span');
  span.className = 'mymention';
  span.setAttribute('data-mention-id', userInfo.id);
  span.appendChild(editor.getDoc().createTextNode('@' + userInfo.name));
  return span;
};

const createCard = (userInfo) => {
  const div = document.createElement('div');
  div.innerHTML = (
    '<div class="card">' +
      '<img class="avatar" src="' + userInfo.image + '">' +
      '<h1>' + userInfo.name + '</h1>' +
      '<p>' + userInfo.description + '</p>' +
    '</div>'
  );
  return div;
};

const mentions_select = async (mention, success) => {
  const id = mention.getAttribute('data-mention-id');
  await fetch(`${API_URL}/${id}`)
    .then((response) => response.json())
    .then((userInfo) => {
      const card = createCard({
        id: userInfo.id,
        name: userInfo.name,
        image: userInfo.avatar,
        description: userInfo.custom.role
      });
      success(card);
    })
    .catch((error) => console.error(error));
};

const mentions_menu_hover = async (userInfo, success) => {
  const card = createCard(userInfo);
  success(card);
};

const tinycomments_can_resolve = (req, done, _fail) => {
  const allowed = req.comments.length > 0 && req.comments[0].author === user_id;
  done({ canResolve: allowed });
};

tinymce.init({
  selector: 'textarea#comments-embedded-with-mentions',
  plugins: [ 'tinycomments', 'mentions', 'help', 'code', 'quickbars', 'link', 'lists', 'image' ],
  toolbar: 'addcomment showcomments code | bold italic underline',
  menubar: 'file edit view insert format tools tc help',
  menu: {
    tc: {
      title: 'TinyComments',
      items: 'addcomment showcomments deleteallconversations'
    }
  },
  quickbars_selection_toolbar: 'alignleft aligncenter alignright | addcomment showcomments',
  quickbars_image_toolbar: 'alignleft aligncenter alignright | rotateleft rotateright | imageoptions',

  tinycomments_mode: 'embedded',
  sidebar_show: 'showcomments',
  tinycomments_mentions_enabled: true,
  tinycomments_can_resolve,
  tinycomments_author: user_id,
  tinycomments_author_name: 'James Wilson',
  tinycomments_author_avatar: 'https://sneak-preview.tiny.cloud/demouserdirectory/images/employee_james-wilson_128_52f19412.jpg',

  mentions_item_type: 'profile',
  mentions_min_chars: 0,
  mentions_selector: '.mymention',
  mentions_fetch,
  mentions_menu_hover,
  mentions_menu_complete,
  mentions_select,
});
```

## Required Mentions Options

These configuration options are required for use of the `mentions` plugin.

- [`mentions_fetch`](#mentions_fetch)

### `mentions_fetch`

This option lets you request a list of users from your server that match a search query. The callback gets passed two parameters: one is the search query object, the other is the success callback to execute with the results. The query object has a term property that contains what the user has typed after the "@" sign.

The success call should contain an array of users.

> **Note:** Only the first ten (10) users listed in the array are displayed in the Mentions UI presented to end-users.
For information on the user properties to pass to the success callback for the available mentions item types (`mentions_item_type`), see: [User properties](../mentions/#user-properties).

**Type:** `Function`

#### Example: using `mentions_fetch`

```js
const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';

const mentions_fetch = async (query, success) => {
  const searchPhrase = query.term.toLowerCase();
  await fetch(`${API_URL}?q=${encodeURIComponent(searchPhrase)}`)
    .then((response) => response.json())
    .then((users) => success(users.data.map((userInfo) => ({
      id: userInfo.id,
      name: userInfo.name,
      image: userInfo.avatar,
      description: userInfo.custom.role
    }))))
    .catch((error) => console.log(error));
};

tinymce.init({
  selector: 'textarea',
  plugins: 'mentions',
  mentions_fetch
});
```
The `success` callback can be passed an optional array of extra items. When clicked, the menu reloads and passes additional query parameters to the fetch function. The extra items can be used to search with different queries or show additional results, such as a full text search (which is slower to fetch). Each extra item should contain:

- A "text" property for the content to be displayed in the menu.
- A "meta" property for that will be passed using the fetch query parameter.

#### Example with extras

```js
const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';

const mentions_fetch = async (query, success) => {
  const searchPhrase = query.term.toLowerCase();
  await fetch(`${API_URL}?q=${encodeURIComponent(searchPhrase)}`)
    .then((response) => response.json())
    .then((users) => {
      const mentions = users.data.map((userInfo) => ({
        id: userInfo.id,
        name: userInfo.name,
        image: userInfo.avatar,
        description: userInfo.custom.role
        ...(query.meta && query.meta.email)
          ? { email: userInfo.custom.email }
          : {}
      }));
      const extras = [{
        text: 'Include email...',
        meta: { email: true }
      }];
      success(mentions, extras);
    })
    .catch((error) => console.log(error));
};

tinymce.init({
  selector: 'textarea',
  plugins: 'mentions',
  mentions_fetch
});
```

## Required Comments options in callback mode

When using callback mode, the Comments plugin requires callback functions for the following options:

- [`tinycomments_create`](#tinycomments_create)
- [`tinycomments_reply`](#tinycomments_reply)
- [`tinycomments_edit_comment`](#tinycomments_edit_comment)
- [`tinycomments_delete_comment`](#tinycomments_delete_comment)
- [`tinycomments_delete`](#tinycomments_delete)
- [`tinycomments_delete_all`](#tinycomments_delete_all)
- [`tinycomments_lookup`](#tinycomments_lookup)

### `tinycomments_create`

The Comments plugin uses the `tinycomments_create` function to create a comment.

The `tinycomments_create` function saves the comment as a new conversation and returns a unique conversation ID via the `done` callback. If an unrecoverable error occurs, it should indicate this with the fail callback.

The `tinycomments_create` function is given a request (req) object as the first parameter, which has these fields:

- `content`: The content of the comment to create.
- `createdAt`: The date the comment was created.

The `done` callback should accept the following object:

```js
{
  conversationUid: string, // the new conversation uid
  // Optional error callback which will be run if the new conversation could not be created
  onError: (err) => { ... },
  // Optional success callback which will be run when the new conversation is successfully created
  onSuccess: (uid) => { ... }
}
```
For example:
```js
const create_comment = (ref, done, fail) => {
  const { content, createdAt } = ref;

  fetch('https://api.example/conversations/', {
    method: 'POST',
    body: JSON.stringify({ content: content, createdAt: createdAt }),
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error('Failed to create comment');
      }
      return response.json();
    })
    .then((ref2) => {
      let conversationUid = ref2.conversationUid;
      done({ conversationUid: conversationUid });
    })
    .catch((e) => {
      fail(e);
    });
}

tinymce.init({
  selector: 'textarea', // change this value according to your HTML
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment, // Add the callback to TinyMCE
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread,
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_reply`

The Comments plugin uses the `tinycomments_reply` function to reply to a comment.

The `tinycomments_reply` function saves the comment as a reply to an existing conversation and returns via the `done` callback once successful. Unrecoverable errors are communicated to TinyMCE by calling the `fail` callback instead.

The `tinycomments_reply` function is given a request (req) object as the first parameter, which has these fields:

- `conversationUid`: The uid of the conversation the reply is targeting.
- `content`: The content of the comment to create.
- `createdAt`: The date the comment was created (ISO 8601 date string) format.

The `done` callback should accept the following object:

```js
{
  commentUid: string, // the new comment uid
  author: string, // the id of the current author
  authorName: string // the name of the current author
}
```
For example:
```js
const reply_comment = (ref, done, fail) => {
  const { conversationUid, content, createdAt } = ref;

  fetch(`https://api.example/conversations/${conversationUid}`, {
    method: 'POST',
    body: JSON.stringify({ content: content, createdAt: createdAt }),
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error('Failed to reply to comment');
      }
      return response.json();
    })
    .then((ref2) => {
      let commentUid = ref2.commentUid;
      done({
        commentUid: replyUid,
        author: currentUser.id,
        authorName: currentUser.fullName
      });
    })
    .catch((e) => {
      fail(e);
    });
}

tinymce.init({
  selector: 'textarea', // change this value according to your HTML
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment, // Add the callback to TinyMCE
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread,
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_edit_comment`

The Comments plugin uses the `tinycomments_edit_comment` function to edit a comment.

The `tinycomments_edit_comment` function allows updating or changing existing comments and returns via the `done` callback once successful. Unrecoverable errors are communicated to TinyMCE by calling the `fail` callback instead.

The `tinycomments_edit_comment` function is given a request (req) object as the first parameter, which has these fields:

- `conversationUid`: The uid of the conversation the reply is targeting.
- `commentUid`: The uid of the comment to edit (it can be the same as `conversationUid` if editing the first comment in a conversation).
- `content`: The content of the comment to create.
- `modifiedAt`: The date the comment was modified.

The `done` callback should accept the following object:

```js
{
  canEdit: boolean, // whether or not the Edit succeeded
  reason: string? // an optional string explaining why the edit was not allowed (if canEdit is false)
}
```
For example:
```js
const edit_comment = (ref, done, fail) => {
  const { conversationUid, commentUid, content, modifiedAt } = ref;

  fetch(
    `https://api.example/conversations/${conversationUid}/${commentUid}`,
    {
      method: 'PUT',
      body: JSON.stringify({ content: content, modifiedAt: modifiedAt }),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    }
  )
    .then((response) => {
      if (!response.ok) {
        throw new Error('Failed to edit comment');
      }
      return response.json();
    })
    .then((ref2) => {
      let canEdit = ref2.canEdit;
      done({ canEdit: canEdit });
    })
    .catch((e) => {
      fail(e);
    });
}

tinymce.init({
  selector: 'textarea', // change this value according to your HTML
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment, // Add the callback to TinyMCE
  tinycomments_delete: delete_comment_thread,
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_delete_comment`

The `tinycomments_delete_comment` function should asynchronously return a flag indicating whether the comment or comment thread was removed using the `done` callback. Unrecoverable errors are communicated to TinyMCE by calling the `fail` callback instead.

The `tinycomments_delete_comment` function is given a request (req) object as the first parameter, which has these fields:

- `conversationUid`: The uid of the conversation the reply is targeting.
- `commentUid`: The uid of the comment to delete (cannot be the same as `conversationUid`).

The `done` callback should accept the following object:

```js
{
  canDelete: boolean, // whether or not an individual comment can be deleted
  reason: string? // an optional reason explaining why the delete was not allowed (if canDelete is false)
}
```

> **Note:** Failure to delete due to permissions or business rules is indicated by "false", while unexpected errors should be indicated using the "fail" callback.
For example:
```js
const delete_comment = (ref, done, fail) => {
  const { conversationUid, commentUid } = ref;

  fetch(
    `https://api.example/conversations/${conversationUid}/${commentUid}`,
    {
      method: 'DELETE',
    }
  ).then((response) => {
    if (response.ok) {
      done({ canDelete: true });
    } else if (response.status === 403) {
      done({ canDelete: false });
    } else {
      fail(new Error('Something has gone wrong...'));
    }
  });
}

tinymce.init({
  selector: 'textarea', // change this value according to your HTML
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread, // Add the callback to TinyMCE
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_delete`

The `tinycomments_delete` function should asynchronously return a flag indicating whether the comment thread was removed using the `done` callback. Unrecoverable errors are communicated to TinyMCE by calling the `fail` callback instead.

The `tinycomments_delete` function is passed a (`req`) object as the first parameter, which contains the following key-value pair:

- `conversationUid`: The uid of the conversation the reply is targeting.

The `done` callback should accept the following object:

```js
{
  canDelete: boolean // whether or not the conversation can be deleted
  reason: string? // an optional string explaining why the delete was not allowed (if canDelete is false)
}
```

> **Note:** Failure to delete due to permissions or business rules is indicated by "false", while unexpected errors should be indicated using the "fail" callback.
For example:

```js
const delete_comment_thread = (ref, done, fail) => {
  const conversationUid = ref.conversationUid;
  fetch(`https://api.example/conversations/${conversationUid}`, {
    method: 'DELETE',
  }).then((response) => {
    if (response.ok) {
      done({ canDelete: true });
    } else if (response.status === 403) {
      done({ canDelete: false });
    } else {
      fail(new Error('Something has gone wrong...'));
    }
  });
}

tinymce.init({
  selector: '#editor',
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread, // Add the callback to TinyMCE
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_delete_all`

The `tinycomments_delete_all` function should asynchronously return a flag indicating whether all the comment threads were removed using the `done` callback. Unrecoverable errors are communicated to TinyMCE by calling the `fail` callback instead.

The `tinycomments_delete_all` function is given a request (req) object as the first parameter with no fields.

The `done` callback should accept the following object:

```js
{
  canDelete: boolean, // whether or not all conversations can be deleted
  reason: string? // an optional string explaining why the deleteAll was not allowed (if canDelete is false)
}
```

> **Note:** Failure to delete due to permissions or business rules should be indicated by `canDelete: false`, while unexpected errors should be indicated using the `fail` callback.
For example:
```js
const delete_all_comment_threads = (_req, done, fail) => {
  fetch('https://api.example/conversations', {
    method: 'DELETE',
  }).then((response) => {
    if (response.ok) {
      done({ canDelete: true });
    } else if (response.status === 403) {
      done({ canDelete: false });
    } else {
      fail(new Error('Something has gone wrong...'));
    }
  });
}

tinymce.init({
  selector: 'textarea', // change this value according to your HTML
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread,
  tinycomments_delete_all: delete_all_comment_threads, // Add the callback to TinyMCE
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment,
  tinycomments_fetch: fetch_comments // Optional callback
});
```

### `tinycomments_lookup`

The Comments plugin uses the `tinycomments_lookup` function to retrieve one existing conversation using a conversation’s unique ID.

The **Display names** configuration must be considered for the `tinycomments_lookup` function:

Display names The Comments plugin uses a simple string for the display name. For the `lookup` function, Comments expects each comment to contain the author’s display name, not a user ID, as Comments does not know the user identities. The `lookup` function should be implemented considering this and resolve user identifiers to an appropriate display name.

The conventional conversation object structure that should be returned via the `done` callback is as follows:

The `tinycomments_lookup` function is passed a (`req`) object as the first parameter, which contains the following key-value pair:

`conversationUid` The uid of the conversation the reply is targeting.

The `done` callback should accept the following object:

```js
{
 conversation: {
   uid: string, // the uid of the conversation,
   comments: [
    {
      author: string, // author of first comment
      authorName: string, // optional - Display name to use instead of author. Defaults to using `author` if not specified
      authorAvatar: string, // optional - URL to the author's avatar. If not provided an automated avatar will be generated
      createdAt: date, // when the first comment was created
      content: string, // content of first comment
      modifiedAt: date, // when the first comment was created/last updated
      uid: string // the uid of the first comment in the conversation
    },
    {
      author: string, // author of second comment
      authorName: string, // optional - Display name to use instead of author. Defaults to using `author` if not specified
      authorAvatar: string, // optional - URL to the author's avatar. If not provided an automated avatar will be generated
      createdAt: date, // when the second comment was created
      content: string, // content of second comment
      modifiedAt: date, // when the second comment was created/last updated
      uid: string // the uid of the second comment in the conversation
    }
  ]
 }
}
```

> **Note:** The dates should use [ISO 8601 format](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString). This can be generated in JavaScript with: `new Date().toISOString()`.
> 
> The author avatar feature is only available in TinyMCE 6.1 or higher and if provided:
> 
> - will be scaled to a 36px diameter circle; and
> - can be any filetype able to be wrapped in an `<img>` element.
For example:
```js
const lookup_comment = ({ conversationUid }, done, fail) => {
  const lookup = async () => {
    const convResp = await fetch(
      `https://api.example/conversations${conversationUid}`
    );
    if (!convResp.ok) {
      throw new Error('Failed to get conversation');
    }
    const comments = await convResp.json();
    const usersResp = await fetch('https://api.example/users/');
    if (!usersResp.ok) {
      throw new Error('Failed to get users');
    }
    const { users } = await usersResp.json();
    const getUser = (userId) => users.find((u) => u.id === userId);
    return {
      conversation: {
        uid: conversationUid,
        comments: comments.map((comment) => {
          const user = getUser(comment.author);
          return {
            ...comment,
            content: comment.content,
            authorName: user?.displayName,
            authorAvatar: user?.avatarUrl
          };
        })
      }
    };
  };

  lookup()
    .then((data) => {
      console.log(`Lookup success ${conversationUid}`, data);
      done(data);
    })
    .catch((err) => {
      console.error(`Lookup failure ${conversationUid}`, err);
      fail(err);
    });
};

tinymce.init({
  selector: '#editor',
  plugins: 'tinycomments',
  tinycomments_mode: 'callback',
  tinycomments_create: create_comment,
  tinycomments_reply: reply_comment,
  tinycomments_edit_comment: edit_comment,
  tinycomments_delete: delete_comment_thread,
  tinycomments_delete_all: delete_all_comment_threads,
  tinycomments_delete_comment: delete_comment,
  tinycomments_lookup: lookup_comment, // Add the callback to TinyMCE
  tinycomments_fetch: fetch_comments // Optional callback
});
```

## Required Comments options for embedded mode

When using embedded mode, the Comments plugin requires the following options:

- [`tinycomments_author`](#tinycomments_author)
- [`tinycomments_author_name`](#tinycomments_author_name)

### `tinycomments_author`

This option sets the author id to be used when creating or replying to comments.

**Type:** `String`

**Default value:** `'Anon'`

#### Example: using `tinycomments_author`

```js
tinymce.init({
  selector: 'textarea',  // change this value according to your html
  plugins: 'tinycomments',
  toolbar: 'addcomment showcomments',
  tinycomments_mode: 'embedded',
  tinycomments_author: 'embedded_journalist',
});
```

### `tinycomments_author_name`

*Optional*: This option sets the author’s display name to be used when creating or replying to comments. If this option is omitted, the author `id` is used instead.

**Type:** `String`

#### Example: using `tinycomments_author_name`

```js
tinymce.init({
  selector: 'textarea',  // change this value according to your html
  plugins: 'tinycomments',
  toolbar: 'addcomment showcomments',
  tinycomments_mode: 'embedded',
  tinycomments_author: 'embedded_journalist',
  tinycomments_author_name: 'Embedded Journalist',
});
```

## Additional options

- [`tinycomments_mentions_enabled`](#tinycomments_mentions_enabled)

### `tinycomments_mentions_enabled`

The Comments plugin offers the `tinycomments_mentions_enabled` option to control whether the [Mentions](../mentions/) plugin will be incorporated into the Comments plugin, when both plugins are included in the configuration.

**Type:** `Boolean`

**Possible values:** `true`, `false`

**Default value:** `true`

#### Example: using `tinycomments_mentions_enabled` option

```js
tinymce.init({
  selector: 'textarea',  // change this value according to your html
  plugins: 'tinycomments mentions',
  toolbar: 'addcomment showcomments',
  tinycomments_mentions_enabled: true,
  tinycomments_mode: 'embedded',
  tinycomments_author: 'johnsmith',
  tinycomments_author_name: 'John Smith',
  mentions_fetch,
  mentions_menu_complete,
  mentions_menu_hover,
  mentions_select
});
```

## APIs

The Comments plugin provides the [`getEventLog()`](../comments-commands-events-apis/#getEventLog) API, as well as an annotator named [`'tinycomments'`](../comments-commands-events-apis/#tinycomments-annotator) created using the [`editor.annotator` API](../annotations/).

### getEventLog()

> **Note:** This feature is only available for TinyMCE 6.1 and later.
The `getEventLog` returns a log that contains information and timestamps of all changes to comments, including when:

- A new comment is added.

```js
{
  "type": "create",
  "timestamp": "2024-10-01T03:07:53.771Z",
  "conversationUid": "annotation-r1nn5xdo5ye",
  "conversationContext": "Welcome",
  "conversationContent": "new comment",
  "conversationAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  }
},
```

- A comment is edited.

```js
{
  "type": "edit-comment",
  "timestamp": "2024-10-01T03:08:06.551Z",
  "conversationUid": "annotation-r1nn5xdo5ye",
  "commentUid": "annotation-r1nn5xdo5ye",
  "conversationContext": "Welcome",
  "conversationContent": "new comment",
  "conversationCreatedAt": "2024-10-01T03:07:53.771Z",
  "commentContent": "new comment (Edit comment)",
  "commentAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  },
  "conversationAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  }
},
```

- A reply to a comment is added.

```js
{
  "type": "reply",
  "timestamp": "2024-10-01T03:07:53.771Z",
  "conversationUid": "annotation-r1nn5xdo5ye",
  "commentUid": "annotation-uh00rb41kma",
  "conversationContext": "Welcome",
  "conversationContent": "new comment (Edit comment)",
  "conversationCreatedAt": "2024-10-01T03:07:53.771Z",
  "commentContent": "reply to existing comment",
  "commentAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  },
  "conversationAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  }
},
```

- A comment is resolved.

```js
{
  "type": "resolve",
  "timestamp": "2024-10-01T03:08:25.783Z",
  "conversationUid": "annotation-r1nn5xdo5ye",
  "conversationContext": "Welcome",
  "conversationContent": "new comment (Edit comment)",
  "conversationAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  }
},
```

- A comment is deleted.

```js
{
  "type": "delete-comment",
  "timestamp": "2024-10-01T03:08:23.292Z",
  "conversationUid": "annotation-r1nn5xdo5ye",
  "commentUid": "annotation-uh00rb41kma",
  "conversationContext": "Welcome",
  "conversationContent": "new comment (Edit comment)",
  "commentContent": "reply to existing comment",
  "commentAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  },
  "conversationAuthor": {
      "author": "DEMO USER",
      "authorName": "DEMO USER"
  }
},
```
The event log can be retrieved either in full or with the `after` option, which restricts the returned list to Comment events after a time-stamp date in the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) format, both shown in the following:

#### With the Mentions plugin

When the [Mentions](../mentions/) plugin is enabled, each of the above events will include the `mentionedUids` property, which contains an array of UIDs mentioned in the comment. The `mentionedUids` property is only included when the [Mentions](../mentions/) plugin is enabled.

It is recommended to use this API to retrieve which users have been mentioned in comments.

> **Note:** The `mentionedUids` array captures strings following the `@` symbol without verifying if they correspond to valid user IDs. It is the integrator’s responsibility to validate these strings against the database to ensure they represent valid users.
> 
> For guidance on retrieving and verifying the `mentionedUids` array, refer to the [getEventLog example](#example-using-geteventlog).

#### Example: using `getEventLog()`

```js
// Sample user database
const userDb = {
    "johnsmith": {
        "id": "johnsmith",
        "name": "John Smith",
        "fullName": "John Smith",
        "description": "Company Founder",
        "image": "https://i.pravatar.cc/150?img=11"
    },
    "jennynichols": {
        "id": "jennynichols",
        "name": "Jenny Nichols",
        "fullName": "Jenny Nichols",
        "description": "Marketing Director",
        "image": "https://i.pravatar.cc/150?img=10"
    }
};

const comments = tinymce.activeEditor.plugins.tinycomments;

console.log(comments.getEventLog());
console.log(comments.getEventLog(
  { after: '2022-02-22T12:34:56Z' }  // ISO-8601 standard: YYYY-MM-DDThh:mm:ssZ
));

const eventLog = comments.getEventLog();
const events = eventLog.events;

// Ensure that the mentioned users are valid users in the database
const validatedEvents = JSON.parse(JSON.stringify(events));
validatedEvents.forEach((event) => {
  // Filter out invalid users - change this to your own validation logic
  event.mentionedUids = event.mentionedUids ? event.mentionedUids.filter((uid) => userDb[uid]) : undefined;
});

const mentionedUsers = validatedEvents.flatMap(({ mentionedUids }) => mentionedUids || []);
console.log(mentionedUsers);

let whoMentionedWho = {};
validatedEvents.forEach((event) => {
  if ((event.type === "create" || event.type === "reply") && event.mentionedUids !== undefined) {
    console.log(event);
    if (whoMentionedWho[event.conversationAuthor.author] === undefined) {
      whoMentionedWho[event.conversationAuthor.author] = [...event.mentionedUids];
    } else {
      whoMentionedWho[event.conversationAuthor.author].push(...event.mentionedUids);
    }
  }
});
console.log(whoMentionedWho);
```
