Files
habitica/website/client/src/libs/highlightUsers.js
T
kareenf 657327edd7 Fixes issue where usernames that are sandwiched with underscores are not properly formatted [fixes #12033] (#12071)
* For some reason this file shows as modified, however I checked and it seems as though the same code chunk was 'deleted' and 'added' back in

* Added in logic to take care of issue pertaining to usernames with underscores such as @_spider_ was not showing up in the proper username format

* Added component test to test underscores in username issue

* I accidentally forgot to change the expected result to be @_user_

* Fixed strange spacing issue in profile.vue to match the original

* Another place where I needed to put _user_

* Accidentally left in describe.only in highlightUsers.spec.js,so removed .only

* Added in suggestions from @benkelaar and added in support for fixing double underscore sandwiched usernames which is Markdown's way of bolding

* Added component test to test that usernames sandwiched with double underscores are properly formatted

* Added fixes to test case input and variable mismatch in function

* Updated expect result statement to not be a user mention instance

Co-authored-by: Kareen <kareenf@umich.edu>
2020-04-17 21:45:01 +02:00

27 lines
1.2 KiB
JavaScript

import escapeRegExp from 'lodash/escapeRegExp';
const optionalAnchorTagRegExStr = '(<\\w[^>]*)?'; // everything including the anchor tag is recognized
const mentionRegExStr = '(@(?:<(?:em|strong)>)?[\\w-]+(?:<\\/(?:em|strong)>)?)';
const optionalPostMentionRegExStr = '(\\.\\w+)?'; // like dot-TLD
const finalMentionRegEx = new RegExp(`${optionalAnchorTagRegExStr}${mentionRegExStr}${optionalPostMentionRegExStr}`, 'gi');
export function highlightUsers (text, userName, displayName) { // eslint-disable-line import/prefer-default-export, max-len
const currentUser = [`@${userName}`, `@${displayName}`].map(escapeRegExp);
text = text.replace(finalMentionRegEx, (fullMatched, preMention, mentionStr, postMention) => { // eslint-disable-line no-param-reassign, max-len
if ((preMention && preMention.includes('<a')) || Boolean(postMention)) {
return fullMatched;
}
let fixedStr = mentionStr.replace(/<\/?em>/g, '_');
fixedStr = fixedStr.replace(/<\/?strong>/g, '__');
const isUserMention = currentUser.includes(fixedStr) ? 'at-highlight' : '';
return fullMatched.replace(mentionStr, `<span class="at-text ${isUserMention}">${fixedStr}</span>`);
});
return text;
}