Report an issue

guideIntegrating comments with your application

This guide describes integrating comments as a standalone plugin. If you are using real-time-collaboration, refer to the Real-time collaborative features integration guide.

The Comments plugin provides an API for managing comments added to the document. Through this API you can add, remove, or update comments in the rich-text editor. However, all these changes are local (unsaved) and will disappear after the editor is destroyed. To read the comments data from your own database and save them there you need to provide a proper integration.

This guide will discuss two ways to integrate CKEditor 5 with your comments data source:

The adapter integration is the recommended one because it gives you better control over the data.

# Before you start

Comments is a commercial plugin and a license key is needed to authenticate. If you do not have one, please contact us.

Before you start creating an integration, there are a few concepts you should be familiar with. This guide will explain how to create a custom build with the comments plugin, what data structure the comments use and what the comments plugin API looks like.

Make sure that you understand all of these concepts before you proceed to the integration.

Complementary to this guide, we provide ready-to-use samples available for download. You may use the samples as an example or as a starting point for your own integration.

# Prepare a custom build

The comments plugin is not included in any CKEditor 5 build. To enable it, you need to create a custom CKEditor 5 build that includes the comments plugin.

git clone -b stable https://github.com/ckeditor/ckeditor5-build-classic.git ckeditor5-with-comments
cd ckeditor5-with-comments
npm install

You need to install the @ckeditor5/ckeditor5-comments package using npm:

npm install --save-dev @ckeditor/ckeditor5-comments

To make comments work, you need to import the Comments plugin and add it to the list of plugins.

An updated src/ckeditor.js should look like this:

import ClassicEditorBase from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';

import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import Image from '@ckeditor/ckeditor5-image/src/image';

import Comments from '@ckeditor/ckeditor5-comments/src/comments';

export default class ClassicEditor extends ClassicEditorBase {}

// Plugins to include in the build.
ClassicEditor.builtinPlugins = [ Essentials, Paragraph, Bold, Italic, Image, Comments ];

// Editor configuration.
ClassicEditor.defaultConfig = {
    language: 'en'
};

Note that your custom build needs to be bundled using webpack.

npm run build

Read more about installing plugins.

# Core setup

For completeness sake, examples below implement the wide sidebar display mode for comment threads. If you want to use the inline display mode, remove parts of the snippets that set up the sidebar.

When you have the comments package included in your custom build, prepare an HTML structure for the sidebar. After that you can enable the comments plugin. Proceed as follows:

  • Set up a two-column layout.
  • Add the sidebar configuration.
  • Add the comment button to the toolbar. If you use the ImageToolbar plugin, also add the comment button to the image toolbar.
  • Add your licenseKey. If you do not have a key yet, please contact us.

Edit the sample/index.html file as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 collaboration with comments</title>
    <style type="text/css">
     #container {
        /* To create the column layout. */
        display: flex;

        /* To make the container relative to its children. */
        position: relative;
     }

     #container .ck.ck-editor {
        /* To stretch the editor to max 700px
            (just to look nice for this example but it can be any size). */
        width: 100%;
        max-width: 700px;
     }

     #sidebar {
        /* Set some size for the sidebar (it can be any). */
        min-width: 300px;

        /* Add some distance. */
        padding: 0 10px;
     }
    </style>
</head>
<body>

<div id="container">
    <div id="editor"></div>
    <div id="sidebar"></div>
</div>
<script src="../build/ckeditor.js"></script>
<script>
    const initialData =
        `<h2>
            <comment id="thread-1" type="start"></comment>
            Bilingual Personality Disorder
            <comment id="thread-1" type="end"></comment>
        </h2>
        <p>
            This may be the first time you hear about this made-up disorder but it actually isn’t so far from the truth.
            As recent studies show, the language you speak has more effects on you then you realise.
            According to the studies, the language a person speaks affects their cognition,
            behaviour, emotions and hence <strong>their personality</strong>.
        </p>
        <p>
            This shouldn’t come as a surprise
            <a href="https://en.wikipedia.org/wiki/Lateralization_of_brain_function">since we already know</a>
            that different regions of the brain becomes more active depending on the activity.
            Since structure, information and especially <strong>the culture</strong> of languages varies substantially
            and the language a person speaks is a essential element of daily life.
        </p>`;

    ClassicEditor.create( document.querySelector( '#editor' ), {
        initialData,
        licenseKey: 'your-license-key',
        sidebar: {
            container: document.querySelector( '#sidebar' )
        },
        toolbar: {
            items: [ 'bold', 'italic', '|', 'comment' ]
        }
    } )
    .catch( error => console.error( error ) );
</script>

</body>
</html>

When you open the sample in the browser you should see the WYSIWYG editor with the comments plugin. However, it still does not load or save any data, so you will get an error when you try to add any comment. You will learn how to add data to the comments plugin later in this guide.

# Comment thread data structure

Below is the data format of a comment thread stored in CKEditor 5.

{
    threadId: 'thread-1', // String
    comments: [           // Array of objects
        {
            commentId: 'comment-1',      // String
            authorId: 'author-id',       // String
            content: 'First comment',    // String
            createdAt: new Date( ... )   // Date instance
        },
        {
            commentId: 'comment-2',      // String
            authorId: 'author-id',       // String
            content: 'Second comment',   // String
            createdAt: new Date( ... )   // Date instance
        }
    ]
}

# Comments API

Below is the public API provided by the Comments plugin.

/**
 * Adds a comment thread with comments to the editor.
 *
 * @param {Object} data The comment thread data.
 * @param {String} data.threadId The ID of the comment thread.
 * @param {Array.<Object>} data.comments Data of all the comments that
 * belong to this thread.
 * @param {String} data.comments[].commentId The comment ID.
 * @param {String} data.comments[].authorId The comment author ID.
 * @param {String} data.comments[].content The comment content.
 * @param {Date} [data.comments[].createdAt] The comment creation date.
 */
addCommentThread( data ) {}

/**
 * Adds a new comment to a comment thread.
 *
 * @param {Object} data The comment data.
 * @param {String} data.threadId The ID of the thread that the comment belongs to.
 * @param {String} data.commentId The comment ID.
 * @param {String} data.authorId The comment author ID.
 * @param {String} data.content The comment content.
 * @param {Date} [data.createdAt] The comment creation date.
 */
addComment( data ) {}

/**
 * Updates a comment.
 *
 * @param {Object} data The comment data.
 * @param {String} data.commentId The ID of the comment to update.
 * @param {String} [data.content] The new content of the comment.
 * @param {Date} [data.createdAt] The new creation date of the comment.
 */
updateComment( data ) {}

/**
 * Removes a comment.
 *
 * @param {String} commentId The ID of the comment to remove.
 */
removeComment( commentId ) {}

/**
 * A generator that iterates over all visible comment
 * threads in the document and returns their data.
 *
 * @returns {Iterable.<Object>}
 */
* getCommentThreads() {}

/**
 * The adapter object. An adapter object should implement a set of functions
 * that will be automatically called by the editor whenever a user changes the
 * comments data. The adapter should communicate with the application database
 * and update information in it. You will see how to set the adapter in details
 * in the next steps.
 */
adapter

/**
 * Called each time the user adds a new comment to a thread.
 *
 * It saves the comment data in the database and returns a promise
 * that should get resolved when the save is completed.
 *
 * If the promise resolves with an object with `createdAt` property, that
 * comment property will be updated in the comment in the editor.
 * This is to update the comment data with server-side information.
 *
 * The `params` object does not expect the `authorId` property.
 * For security reasons, the author of the comment should be set
 * on the server side.
 *
 * The `params` object does not expect the `createdAt` property either.
 * You should use the server-side time generator to ensure that all users
 * see the same date.
 *
 * @param {Object} params
 * @param {String} params.threadId The ID of the comment thread that
 * the new comment belongs to (needed only when adding a new comment).
 * @param {String} params.commentId The comment ID.
 * @param {String} params.content The comment content.
 * @returns {Promise}
 */
adapter.addComment( params ) {}

/**
 * Called each time the user changes the existing comment.
 *
 * It updates the comment data in the database and returns a promise
 * that will be resolved when the update is completed.
 *
 * @param {Object} params
 * @param {String} params.commentId The ID of the comment to update.
 * @param {String} params.content The new content of the comment.
 * @returns {Promise}
 */
adapter.updateComment( params ) {}

/**
 * Called each time the user removes a comment from the thread.
 *
 * It removes the comment from the database and returns a promise
 * that will be resolved when the remove is completed.
 *
 * @param {String} data.commentId The ID of the comment to remove.
 * @returns {Promise}
 */
adapter.removeComment( commentId ) {}

/**
 * Called when the editor needs the data for a comment thread.
 *
 * It returns a promise that resolves with the comment thread data.
 *
 * @param {String} threadId The ID of the thread to fetch.
 * @returns {Promise}
 */
adapter.getCommentThread( threadId ) {}

To use this API you need to get the comments plugin:

// Get the comments plugin:
const commentsPlugin = editor.plugins.get( 'Comments' );

// Add a comment:
commentsPlugin.addComment( data );

// Get all comment threads:
Array.from( commentsPlugin.getCommentThreads() );

// Set the adapter.
commentsPlugin.adapter = {
    ...
};

If editor.plugins.get( 'Comments' ) returns undefined, make sure that your build contains the Comments plugin.

Now you are ready to provide the integration.

# A simple “load and save” integration

In this solution, users and comments data is loaded during the editor initialization and comments data is saved after you finish working with the editor (for example when you submit the form containing the WYSIWYG editor).

This method is recommended only if you can trust your users or if you provide additional validation of the submitted data to make sure that the user changed their comments only.

Complementary to this guide, we provide ready-to-use samples available for download. You may use the samples as an example or as a starting point for your own integration.

# Loading the data

When the comments plugin is already included in the editor, you need to create a plugin which will initialize users and existing comments.

If your plugin needs to request the comments data from the server asynchronously, you can return a Promise from the Plugin.init method to make sure that the editor initialization waits for your data.

First, dump the users and comments data to a variable that will be available for your plugin.

// Application data will be available under a global variable `appData`.
const appData = {
    // Users data.
    users: [
        {
           id: 'user-1',
           name: 'Joe Doe',
           // Note that the avatar is optional.
           avatar: 'https://randomuser.me/api/portraits/thumb/men/26.jpg'
        },
        {
           id: 'user-2',
           name: 'Ella Harper',
           avatar: 'https://randomuser.me/api/portraits/thumb/women/65.jpg'
        }
    ],

    // The ID of the current user.
    userId: 'user-1',

    // Comment threads data.
    commentThreads: [
        {
            threadId: 'thread-1',
            comments: [
                {
                    commentId: 'comment-1',
                    authorId: 'user-1',
                    content: '<p>Are we sure we want to use a made-up disorder name?</p>',
                    createdAt: new Date( '09/20/2018 14:21:53' )
                },
                {
                    commentId: 'comment-2',
                    authorId: 'user-2',
                    content: '<p>Why not?</p>',
                    createdAt: new Date( '09/21/2018 08:17:01' )
                }
            ]
        }
    ],

     // Editor initial data.
     initialData:
         `<h2>
             <comment id="thread-1" type="start"></comment>
             Bilingual Personality Disorder
             <comment id="thread-1" type="end"></comment>
         </h2>
         <p>
             This may be the first time you hear about this made-up disorder but it actually isn’t so far from the truth.
             As recent studies show, the language you speak has more effects on you then you realise.
             According to the studies, the language a person speaks affects their cognition,
             behaviour, emotions and hence <strong>their personality</strong>.
         </p>
         <p>
             This shouldn’t come as a surprise
             <a href="https://en.wikipedia.org/wiki/Lateralization_of_brain_function">since we already know</a>
             that different regions of the brain becomes more active depending on the activity.
             Since structure, information and especially <strong>the culture</strong> of languages varies substantially
             and the language a person speaks is a essential element of daily life.
         </p>`
};

Then, prepare a plugin that will read the data from appData and use the Users and Comments API.

class CommentsIntegration {
    constructor( editor ) {
        this.editor = editor;
    }

    init() {
        const usersPlugin = this.editor.plugins.get( 'Users' );
        const commentsPlugin = this.editor.plugins.get( 'Comments' );

        // Load the users data.
        for ( const user of appData.users ) {
            usersPlugin.addUser( user );
        }

        // Set the current user.
        usersPlugin.defineMe( appData.userId );

        // Load the comment threads data.
        for ( const commentThread of appData.commentThreads ) {
            commentsPlugin.addCommentThread( commentThread );
        }
    }
}

Finally, add the plugin in the editor configuration.

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        initialData: appData.initialData,
        extraPlugins: [ CommentsIntegration ],
        licenseKey: 'your-license-key',
        sidebar: {
            container: document.querySelector( '#sidebar' )
        },
        toolbar: {
            items: [ 'bold', 'italic', '|', 'comment' ]
        }
    } )
    .catch( error => console.error( error ) );

# Saving the data

To save the comments data you need to get it from the Comments API first. To do this, use the getCommentThreads() method.

Then, use the comment threads data to save it in your database in a way you prefer. See the example below.

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        initialData,
        extraPlugins: [ CommentsIntegration ],
        licenseKey: 'your-license-key',
        sidebar: {
            container: document.querySelector( '#sidebar' )
        },
        toolbar: {
            items: [ 'bold', 'italic', '|', 'comment' ]
        }
    } )
    .then( editor => {
        // After the editor is initialized, add an action to be performed after a button is clicked.
        const comments = editor.plugins.get( 'Comments' );

        // Get the data on demand.
        document.querySelector( '#get-data' ).addEventListener( 'click', () => {
            const editorData = editor.data.get();
            const commentThreadsData = Array.from( comments.getCommentThreads() );

            // Now, use `editorData` and `commentThreadsData` to save the data in your application.
            // For example, you can set them as values of hidden input fields.
            console.log( editorData );
            console.log( commentThreadsData );
        } );
    } )
    .catch( error => console.error( error ) );

# Full implementation

Below you can find the final solution.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CKEditor 5 collaboration with comments</title>
        <style type="text/css">
         #container {
            /* To create the column layout. */
            display: flex;

            /* To make the container relative to its children. */
            position: relative;
         }

         #container .ck.ck-editor {
            /* To stretch the editor to max 700px
                (just to look nice for this example but it can be any size). */
            width: 100%;
            max-width: 700px;
         }

         #sidebar {
            /* Set some size for the sidebar (it can be any). */
            min-width: 300px;

            /* Add some distance. */
            padding: 0 10px;
         }
        </style>
    </head>
    <body>
        <button id="get-data">Get editor data</button>

        <div id="container">
            <div id="editor"></div>
            <div id="sidebar"></div>
        </div>
    </body>
    <script src="../build/ckeditor.js"></script>
    <script>
        // Application data will be available under a global variable `appData`.
        const appData = {
            // Users data.
            users: [
                {
                   id: 'user-1',
                   name: 'Joe Doe',
                   // Note that the avatar is optional.
                   avatar: 'https://randomuser.me/api/portraits/thumb/men/26.jpg'
                },
                {
                   id: 'user-2',
                   name: 'Ella Harper',
                   avatar: 'https://randomuser.me/api/portraits/thumb/women/65.jpg'
                }
            ],

            // The ID of the current user.
            userId: 'user-1',

            // Comment threads data.
            commentThreads: [
                {
                    threadId: 'thread-1',
                    comments: [
                        {
                            commentId: 'comment-1',
                            authorId: 'user-1',
                            content: '<p>Are we sure we want to use a made-up disorder name?</p>',
                            createdAt: new Date( '09/20/2018 14:21:53' )
                        },
                        {
                            commentId: 'comment-2',
                            authorId: 'user-2',
                            content: '<p>Why not?</p>',
                            createdAt: new Date( '09/21/2018 08:17:01' )
                        }
                    ]
                }
            ],

            // Editor initial data.
            initialData:
                `<h2>
                    <comment id="thread-1" type="start"></comment>
                    Bilingual Personality Disorder
                    <comment id="thread-1" type="end"></comment>
                </h2>
                <p>
                    This may be the first time you hear about this made-up disorder but it actually isn’t so far from the truth.
                    As recent studies show, the language you speak has more effects on you then you realise.
                    According to the studies, the language a person speaks affects their cognition,
                    behaviour, emotions and hence <strong>their personality</strong>.
                </p>
                <p>
                    This shouldn’t come as a surprise
                    <a href="https://en.wikipedia.org/wiki/Lateralization_of_brain_function">since we already know</a>
                    that different regions of the brain becomes more active depending on the activity.
                    Since structure, information and especially <strong>the culture</strong> of languages varies substantially
                    and the language a person speaks is a essential element of daily life.
                </p>`
        };

        class CommentsIntegration {
            constructor( editor ) {
                this.editor = editor;
            }

            init() {
                const usersPlugin = this.editor.plugins.get( 'Users' );
                const commentsPlugin = this.editor.plugins.get( 'Comments' );

                // Load the users data.
                for ( const user of appData.users ) {
                    usersPlugin.addUser( user );
                }

                // Set the current user.
                usersPlugin.defineMe( appData.userId );

                // Load the comment threads data.
                for ( const commentThread of appData.commentThreads ) {
                    commentsPlugin.addCommentThread( commentThread );
                }
            }
        }

        ClassicEditor
            .create( document.querySelector( '#editor' ), {
                initialData: appData.initialData,
                extraPlugins: [ CommentsIntegration ],
                licenseKey: 'your-license-key',
                sidebar: {
                    container: document.querySelector( '#sidebar' )
                },
                toolbar: {
                    items: [ 'bold', 'italic', '|', 'comment' ]
                }
            } )
            .then( editor => {
                // After the editor is initialized, add an action to be performed after a button is clicked.
                const comments = editor.plugins.get( 'Comments' );

                // Get the data on demand.
                document.querySelector( '#get-data' ).addEventListener( 'click', () => {
                    const editorData = editor.data.get();
                    const commentThreadsData = Array.from( comments.getCommentThreads() );

                    // Now, use `editorData` and `commentThreadsData` to save the data in your application.
                    // For example, you can set them as values of hidden input fields.
                    console.log( editorData );
                    console.log( commentThreadsData );
                } );
            } )
            .catch( error => console.error( error ) );
    </script>
</html>

# Live sample

Console

// Use the `Save data with comments` button to see the result...

# Adapter integration

An adapter integration uses an adapter object — provided by you — to immediately save changes in comments in your data store. This is the recommended way of integrating comments with your application because it lets you handle the client-server communication in a more secure way. For example, you can check user permissions, validate sent data or update the data with information obtained on the server side, like the comment creation date. You will see how to handle the server response in the next steps.

Complementary to this guide, we provide ready-to-use samples available for download. You may use the samples as an example or as a starting point for your own integration.

# Implementation

First, define the adapter using the Comments#adapter setter. Adapter methods are called after a user makes a change in the comments. They allow you to save the change in your database. Each comment action has a separate adapter method. You should implement the following four adapter methods.

On the UI side each change in comments is performed immediately, however, all adapter actions are asynchronous and are performed in the background. Because of this all adapter methods need to return a Promise. When the promise is resolved, it means that everything went fine and a local change was successfully saved in the data store. When the promise is rejected, the editor fires the crash event. When you handle the server response you can decide if the promise should be resolved or rejected.

While any of the adapter action is being performed, a pending action is automatically added to the editor PendingActions plugin, so you do not have to worry that the editor will be destroyed before the adapter action has finished.

Now you are ready to implement the adapter.

// Application data will be available under a global variable `appData`.
const appData = {
    // Users data.
    users: [
        {
           id: 'user-1',
           name: 'Joe Doe',
           // Note that the avatar is optional.
           avatar: 'https://randomuser.me/api/portraits/thumb/men/26.jpg'
        },
        {
           id: 'user-2',
           name: 'Ella Harper',
           avatar: 'https://randomuser.me/api/portraits/thumb/women/65.jpg'
        }
    ],

    // The ID of the current user.
    userId: 'user-1',

    // Editor initial data.
    initialData:
        `<h2>
            <comment id="thread-1" type="start"></comment>
            Bilingual Personality Disorder
            <comment id="thread-1" type="end"></comment>
        </h2>
        <p>
            This may be the first time you hear about this made-up disorder but it actually isn’t so far from the truth.
            As recent studies show, the language you speak has more effects on you then you realise.
            According to the studies, the language a person speaks affects their cognition,
            behaviour, emotions and hence <strong>their personality</strong>.
        </p>
        <p>
            This shouldn’t come as a surprise
            <a href="https://en.wikipedia.org/wiki/Lateralization_of_brain_function">since we already know</a>
            that different regions of the brain becomes more active depending on the activity.
            Since structure, information and especially <strong>the culture</strong> of languages varies substantially
            and the language a person speaks is a essential element of daily life.
        </p>`

};

class CommentsAdapter {
    constructor( editor ) {
        this.editor = editor;
    }

    init() {
        const usersPlugin = this.editor.plugins.get( 'Users' );
        const commentsPlugin = this.editor.plugins.get( 'Comments' );

        // Load the users data.
        for ( const user of appData.users ) {
            usersPlugin.addUser( user );
        }

        // Set the current user.
        usersPlugin.defineMe( appData.userId );

        // Set the adapter to the `Comments#adapter` property.
        commentsPlugin.adapter = {
            addComment( data ) {
                console.log( 'Comment added', data );

                // Write a request to your database here. The returned `Promise`
                // should be resolved when the request has finished.
                // When the promise resolves with the comment data object, it
                // will update the editor comment using the provided data.
                return Promise.resolve( {
                    createdAt: new Date()       // Should be set on the server side.
                } );
            },

            updateComment( data ) {
                console.log( 'Comment updated', data );

                // Write a request to your database here. The returned `Promise`
                // should be resolved when the request has finished.
                return Promise.resolve();
            },

            removeComment( commentId ) {
                console.log( 'Comment removed', commentId );

                // Write a request to your database here. The returned `Promise`
                // should be resolved when the request has finished.
                return Promise.resolve();
            },

            getCommentThread( threadId ) {
                console.log( 'Getting comment thread', threadId );

                // Write a request to your database here. The returned `Promise`
                // should resolve with the comment thread data.
                return Promise.resolve( {
                    threadId: 'thread-1',
                    comments: [
                        {
                            commentId: 'comment-1',
                            authorId: 'user-2',
                            content: '<p>Are we sure we want to use a made-up disorder name?</p>',
                            date: new Date()
                        }
                    ]
                } );
            }
        };
    }
}

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        initialData: appData.initialData,
        extraPlugins: [ CommentsAdapter ],
        licenseKey: 'your-license-key',
        sidebar: {
            container: document.querySelector( '#sidebar' )
        },
        toolbar: {
            items: [ 'bold', 'italic', '|', 'comment' ]
        }
    } )
    .catch( error => console.error( error ) );

The adapter is now ready to use with your rich-text editor.

Below is the final solution.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CKEditor 5 Collaboration with comments</title>
        <style type="text/css">
         #container {
            /* To create the column layout. */
            display: flex;

            /* To make the container relative to its children. */
            position: relative;
         }

         #container .ck.ck-editor {
            /* To stretch the editor to max 700px
                (just to look nice for this example but it can be any size). */
            width: 100%;
            max-width: 700px;
         }

         #sidebar {
            /* Set some size for the sidebar (it can be any). */
            min-width: 300px;

            /* Add some distance. */
            padding: 0 10px;
         }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="editor"></div>
            <div id="sidebar"></div>
        </div>
    </body>
    <script src="../build/ckeditor.js"></script>
    <script>
        // Application data will be available under a global variable `appData`.
        const appData = {
            // Users data.
            users: [
                {
                   id: 'user-1',
                   name: 'Joe Doe',
                   // Note that the avatar is optional.
                   avatar: 'https://randomuser.me/api/portraits/thumb/men/26.jpg'
                },
                {
                   id: 'user-2',
                   name: 'Ella Harper',
                   avatar: 'https://randomuser.me/api/portraits/thumb/women/65.jpg'
                }
            ],

            // The ID of the current user.
            userId: 'user-1',

            // Editor initial data.
            initialData:
                `<h2>
                    <comment id="thread-1" type="start"></comment>
                    Bilingual Personality Disorder
                    <comment id="thread-1" type="end"></comment>
                </h2>
                <p>
                    This may be the first time you hear about this made-up disorder but it actually isn’t so far from the truth.
                    As recent studies show, the language you speak has more effects on you then you realise.
                    According to the studies, the language a person speaks affects their cognition,
                    behaviour, emotions and hence <strong>their personality</strong>.
                </p>
                <p>
                    This shouldn’t come as a surprise
                    <a href="https://en.wikipedia.org/wiki/Lateralization_of_brain_function">since we already know</a>
                    that different regions of the brain becomes more active depending on the activity.
                    Since structure, information and especially <strong>the culture</strong> of languages varies substantially
                    and the language a person speaks is a essential element of daily life.
                </p>`
        };

        class CommentsAdapter {
            constructor( editor ) {
                this.editor = editor;
            }

            init() {
                const usersPlugin = this.editor.plugins.get( 'Users' );
                const commentsPlugin = this.editor.plugins.get( 'Comments' );

                // Load the users data.
                for ( const user of appData.users ) {
                    usersPlugin.addUser( user );
                }

                // Set the current user.
                usersPlugin.defineMe( appData.userId );

                // Set the adapter to the `Comments#adapter` property.
                commentsPlugin.adapter = {
                    addComment( data ) {
                        console.log( 'Comment added', data );

                        // Write a request to your database here. The returned `Promise`
                        // should be resolved when the request has finished.
                        // When the promise resolves with the comment data object, it
                        // will update the editor comment using the provided data.
                        return Promise.resolve( {
                            createdAt: new Date()       // Should be set on the server side.
                        } );
                    },

                    updateComment( data ) {
                        console.log( 'Comment updated', data );

                        // Write a request to your database here. The returned `Promise`
                        // should be resolved when the request has finished.
                        return Promise.resolve();
                    },

                    removeComment( commentId ) {
                        console.log( 'Comment removed', commentId );

                        // Write a request to your database here. The returned `Promise`
                        // should be resolved when the request has finished.
                        return Promise.resolve();
                    },

                    getCommentThread( threadId ) {
                        console.log( 'Getting comment thread', threadId );

                        // Write a request to your database here. The returned `Promise`
                        // should resolve with the comment thread data.
                        return Promise.resolve( {
                            threadId: 'thread-1',
                            comments: [
                                {
                                    commentId: 'comment-1',
                                    authorId: 'user-2',
                                    content: '<p>Are we sure we want to use a made-up disorder name?</p>',
                                    date: new Date()
                                }
                            ]
                        } );
                    }
                };
            }
        }

        ClassicEditor
            .create( document.querySelector( '#editor' ), {
                initialData: appData.initialData,
                extraPlugins: [ CommentsAdapter ],
                licenseKey: 'your-license-key',
                sidebar: {
                    container: document.querySelector( '#sidebar' )
                },
                toolbar: {
                    items: [ 'bold', 'italic', '|', 'comment' ]
                }
            } )
            .catch( error => console.error( error ) );
    </script>
</html>

# Live sample

Pending adapter actions console

// Add, remove or update a comment to see the result...

Since the comments adapter saves the comment changes immediately after they are performed, it is also recommended to use the Autosave plugin to save the editor content after each change.

# Why is there no event when I remove a comment thread?

Note that when you remove the whole thread no event is fired. This is because the thread is never removed from the editor during the editing session. You are able to restore a removed comment thread using undo (Ctrl+Z or Cmd+Z). This is why the editor keeps all removed threads. The same happens when you remove a paragraph with commented text — there will be no event fired because no comment is really removed.

However, to make sure that you do not keep outdated comments in your database you should do a clean-up when the editor is destroyed or closed. You can compare comment threads stored in the document (the IDs of the <comment> tags) with comment threads stored in your database and remove all comments that no longer have a representation in your database.

# PHP integration example

Please refer to Collaboration integration examples for CKEditor 5 repository to find a working end-to-end integration example of collaboration features in a PHP application. Note that it includes both comments and track changes adapters working together.