CometChatUrlTextFormatter
Introduction
CometChatUrlTextFormatter
is a specialized subclass of CometChatTextFormatter
designed to automatically detect URLs in text messages and convert them into clickable links, allowing users to navigate to the web addresses effortlessly within your CometChat application.
Prerequisites
To implement the URL Text Formatter in your chat application, make sure you have:
- A valid CometChat account and application set up.
- Basic knowledge of JavaScript and familiarity with DOM manipulation.
- An understanding of regular expressions for pattern matching.
Implementation
CometChatUrlTextFormatter
utilizes regular expressions to identify URLs and applies styles to make them visually distinct as clickable links. Here's an example of how to extend the CometChatTextFormatter
to create a URL text formatter:
import { CometChatTextFormatter } from "path-to-cometchat-text-formatter";
export class CometChatUrlTextFormatter extends CometChatTextFormatter {
constructor(regexPatterns) {
super();
this.setRegexPatterns(regexPatterns);
}
onRegexMatch(inputText) {
// Override with URL matching and formatting logic
return this.formatUrls(inputText);
}
registerEventListeners(element, classList) {
// Override to handle click events for opening URLs
if (classList.contains("clickable-url")) {
element.addEventListener("click", this.onUrlClick);
}
return element;
}
// Define additional methods as needed...
}
// Example usage:
const urlFormatter = new CometChatUrlTextFormatter([/(https?:\/\/[^\s]+)/g]);
const formattedMessage = urlFormatter.getFormattedText(
"Visit https://www.cometchat.com for more info."
);
console.log(formattedMessage); // Outputs message with clickable link
Customizing Style and Behavior
When implementing the CometChatUrlTextFormatter
, you can customize the appearance of links and the behavior when clicked:
- Modify the
onRegexMatch
method to wrap detected URLs in aspan
element with custom classes for styling. - In
registerEventListeners
, define theonUrlClick
method to handle opening URLs, tracking analytics, or other custom behavior upon click.
Styling Links
Apply CSS to style your clickable links, for example:
.clickable-url {
color: #1a0dab;
text-decoration: underline;
cursor: pointer;
}
Handling Click Events
Implement the onUrlClick
method within your formatter class to define custom logic for when a link is clicked:
onUrlClick(event) {
const url = event.target.dataset.url;
window.open(url, '_blank');
}
UrlFormatterStyle
Styling properties for CometChatUrlTextFormatter
component.
Attributes | Type | Description |
---|---|---|
rightAlignedLinkColor | string | Sets color for links for right aligned messages |
rightAlignedLinkFont | string | Sets font for links for right aligned messages |
leftAlignedLinkColor | string | Sets color for links for left aligned messages |
leftAlignedLinkFont | string | Sets font for links for left aligned messages |