Developing Extensions
Context
FastComments provides the ability to extend our core functionality via scripts we call Extensions.
An Extension
can add additional markup to the comment widget, event listeners, and run arbitrary code.
Here you will find examples of extensions we have in production, as well as documentation on how to write extensions.
The Extension Lifecycle
The script for each extension is fetched and invoked before the comment widget begins fetching the first set of comments and rendering the UI.
On initial load, the following data will be tagged onto the extension object:
config
- A reference to theconfig
object.translations
- A reference to thetranslations
object.commentsById
- A reference to all comments by id.root
- A reference to the root DOM node.
Extensions should override the desired functions, which the comment widget will invoke at the appropriate times.
Defining an Extension
The smallest extension possible would be:
For the sake of this example, save this as my-extension.js
, and make it available at https://example.com/my-extension.min.js
.
This extension does not do anything, except on load it fetches the extension object created by the core comment library.
This Extension
object is a singleton and is not shared with any other extensions.
Next, to load our extension, we have to tell the comment widget about it. For example:
For functional examples, see the next section.
Example Extensions
At FastComments, we write our own extensions, using the same API. You can view the unminified code for these extensions at the following endpoints:
Dark Mode
The Dark Mode extension is conditionally loaded when a "dark" page is detected. This extension simply adds some CSS to the comment widget. This way we do not have to load the dark mode CSS when it is not needed.
https://fastcomments.com/js/comment-ui/extensions/comment-ui.dark.extension.js
Moderation
When the current user is a moderator, we use the moderation extension.
This is a good example for adding click-based event listeners, making API requests, adding to the comment menu and comment areas.
https://fastcomments.com/js/comment-ui/extensions/comment-ui.moderation.extension.js
Live Chat
The Live Chat extension (in combination with other configuration and styling) turns the comment widget into a live chat component.
https://fastcomments.com/js/comment-ui/extensions/live-chat.extension.js
The Extension Object
The extension object consists of the following definition:
The Extension API
Interacting with the Extension
is simple, as we simply define references to functions we want invoked.
To build off the example earlier, let's say we want to add HTML to the top of each comment:
Whenever you return HTML like this, it will get merged into the UI via a dom-diffing algorithm.
Manually triggering the re-render of a comment
We can wait for the initial page load and manually re-render a comment by invoking reRenderComment
: