@mentions in the Ticket Conversations Widget

“Talk is cheap. Show me the code.”
Linus Torvalds

When I first started playing around with @mentions in the Service Portal, I mainly just wanted to see if I could get it to work. Once I was able to figure all of that out, I wanted to work that feature into my form field tag, so I spent a little time working all of that out. But I never returned to the real reason that I want to investigate this capability in the first place, which was to add the @mention feature to the Ticket Conversations widget in the Service Portal. So, let’s do that now.

Now that I know a little bit more about what it takes to do what I want to do, I am going to attempt to be a bit surgical in my interactions with the existing code and try to disturb the existing artifact as little as possible and still accomplish my goal. I still don’t want to alter the original, though, so the first thing that I did was to clone the existing Ticket Conversations widget and create one of my own called Mention Conversations. That gave me my initial canvas on which to work, and left the original widget intact and unmolested. So let’s work our way through the changes from top to bottom.

First, we’ll tackle the Body HTML Template, which contains all of the HTML. The only thing that we really want to change here is the input element for the journal entry (comments). Even though it is only a single line, they still used a TEXTAREA, and we’ll leave that alone, other than to add a few new attributes. Here are the original attributes out of the box:

<textarea
  ng-keypress="keyPress($event)"
  sn-resize-height="trim"
  rows="1"
  id="post-input"
  class="form-control no-resize overflow-hidden"
  ng-model='data.journalEntry'
  ng-model-options='{debounce: 250}'
  ng-attr-placeholder="{{getPlaceholder()}}"
  aria-label="{{getPlaceholder()}}"
  autocomplete="off"
  ng-change="userTyping(data.journalEntry)"/>

To that we will add all of the ment-io attributes needed to support the @mention feature:

<textarea
  ng-keypress="keyPress($event)"
  sn-resize-height="trim"
  rows="1"
  id="post-input"
  class="form-control no-resize overflow-hidden"
  ng-model='data.journalEntry'
  ng-model-options='{debounce: 250}'
  ng-attr-placeholder="{{getPlaceholder()}}"
  aria-label="{{getPlaceholder()}}"
  autocomplete="off"
  ng-change="userTyping(data.journalEntry)"
  mentio=""
  mentio-macros="macros"
  mentio-trigger-char="'@'"
  mentio-items="members"
  mentio-search="searchMembersAsync(term)"
  mentio-template-url="/at-mentions.tpl"
  mentio-select="selectAtMention(item)"
  mentio-typed-term="typedTerm"
  mentio-id="'post-input'"/>

Although that is the only change that we will need to make to the existing HTML code, we also need to provide the template referenced in the mentio-template-url attribute. To include that, we will drop this guy down at the bottom of the existing HTML, just inside the outer, enclosing DIV:

<script type="text/ng-template" id="/at-mentions.tpl">
    <div class="dropdown-menu sn-widget sn-mention">
        <ul class="sn-widget-list_v2">
            <li ng-if="items.length > 0 && !items[0].termLengthIsZero" mentio-menu-item="person" ng-repeat="person in items">
                <div class="sn-widget-list-content sn-widget-list-content_static">
                    <sn-avatar primary="person" class="avatar-small" show-presence="true"></sn-avatar></div>
                <div class="sn-widget-list-content">
                    <span class="sn-widget-list-title" ng-bind-html="person.name"></span>
                    <span class="sn-widget-list-subtitle" ng-if="!person.record_is_visible">Cannot see record</span></div></li>
            <li ng-if="items.length === 1 && items[0].termLengthIsZero">
                <div class="sn-widget-list-content">
                    <span class="sn-widget-list-title sn-widget-list-title_wrap">Enter the name of a person you want to mention</span></div></li>
            <li ng-if="items.length === 0 && items.loading && visible">
                <div class="sn-widget-list-content sn-widget-list-content_static">
                    <span class="sn-widget-list-icon icon-loading"></span></div>
                <div class="sn-widget-list-content">
                    <span class="sn-widget-list-title">Loading...</span></div></li>
            <li ng-if="items.length === 0 && !items.loading">
                <div class="sn-widget-list-content">
                    <span class="sn-widget-list-title">No users found</span></div></li></ul>
    </div>
</script>

That takes care of the HTML, so let’s move on to the CSS. All we need to do there is to include one very important additional CCS file, so we add this line right at the top of that section:

@import url("/css_includes_ng.cssx");

That’s it for the CSS section. The next section is the Server Script, but we don’t need to alter that at all, which is cool, so we will just leave that alone and move on to the Client Controller. Down at the very bottom, we will add three new functions:

$scope.searchMembersAsync = function(term) {
	$scope.userSysId = window.NOW.user_id;
	$scope.members = [];
	$scope.members.loading = true;
	clearTimeout($scope.typingTimer);
	if (term.length === 0) {
		$scope.members = [{
			termLengthIsZero: true
		}];
		$scope.members.loading = false;
	} else {
		$scope.typingTimer = setTimeout(function() {
			snMention.retrieveMembers('sys_id', $scope.userSysId, term).then(function(members) {
				$scope.members = members;
				$scope.members.loading = false;
			}, function () {
				$scope.members = [{
					termLengthIsZero: true
				}];
				$scope.members.loading = false;
			});
		}, 500);
	}
};

$scope.selectAtMention = function(item) {
	if (!$scope.mentionMap) {
		$scope.mentionMap = {};
	}
	if (item.termLengthIsZero) {
		return (item.name || "") + "\n";
	}
	$scope.mentionMap[item.name] = item.sys_id;
	return "@[" + item.name + "]";
};

function expandMentions(entryText) {
	return entryText.replace(/@\[(.+?)\]/gi, function (mention) {
		var response = mention;
		var mentionedName = mention.substring(2, mention.length - 1);
		if ($scope.mentionMap[mentionedName]) {
			response = "@[" + $scope.mentionMap[mentionedName] + ":" + mentionedName + "]";
		}
		return response;
	});
}

The first two are referenced in the ment-io attributes that we added to the TEXTAREA in the HTML template. The last one is used just before saving the comment, so we have to hunt down the line that sends that data back to server for posting to the record, and insert a call to that function. That logic is in the existing post function, and out of the box looks like this:

input = input.trim();
$scope.data.journalEntry = input;

We’ll tweak that just a bit to expand the mentions before sending the comments off to the server to be written to the database:

input = expandMentions(input.trim());
$scope.data.journalEntry = input;

One last thing that we will need to do with the client side code is to add the snMention object to the long list of arguments passed into the controller function. This is necessary because that object is referenced by our new searchMembersAsync function. That should wrap things up one the client side, though, which is the last thing that we need to change, so all that is left to do now is to drop this baby onto the page, fire it up, and give it a spin.

First, we need to find an Incident on the Service Portal to bring up on the ticket page, and then we start typing with an @ sign to activate the pop-up pick list from which you can select a person. So far, so good:

Selecting a person to @mention in the comment

Selecting the person puts square brackets around the person’s name while in the input element, which you can see before hitting Send.

@mentions in the input element before saving

Clicking on the Send button triggers the expandMentions function that we added to the controller, which then adds the sys_id of the User inside those square brackets, all of which gets sent over to the server side to be written to the database. A lot of things happen after that which are not a part of this widget, but when all is said and done, the comment comes back out as part of the time line, and both the sys_id and square brackets are long gone at this point.

New comment added to the timeline

In addition to the removal of the square brackets and sys_id, one other thing that happens when you add an @mention to a comment is that the person mentioned gets notified. If you look in the system email logs, you can find a record of this notification, which comes out like this with an out-of-the-box template:

Standard notice to those @mentioned

The cool thing about that was that we didn’t have to add any additional code or do anything special to make that happen — we just had to pass the @mention details in the proper format and things took care of themselves from there. Pretty slick.

Well, that’s about all there is to that. If you want all the parts and pieces needed to make this work, here is an Update Set. I tried my best to have a fairly light touch as far as the existing code goes, but if you have any ideas on how to make it even better, I would love to hear about them.