From 214e48835a55be9ca1800740fd229b030d3c24a8 Mon Sep 17 00:00:00 2001 From: hmhealey Date: Fri, 11 Sep 2015 11:21:34 -0400 Subject: Added highlighting of search terms to the new text formatting --- web/react/utils/text_formatting.jsx | 47 ++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 6 deletions(-) (limited to 'web/react') diff --git a/web/react/utils/text_formatting.jsx b/web/react/utils/text_formatting.jsx index 930a6bbfb..48db78abc 100644 --- a/web/react/utils/text_formatting.jsx +++ b/web/react/utils/text_formatting.jsx @@ -13,16 +13,15 @@ export function formatText(text, options = {}) { output = stripAtMentions(output, tokens); output = stripSelfMentions(output, tokens); output = stripHashtags(output, tokens); + output = highlightSearchTerm(output, tokens, options.searchTerm); output = replaceTokens(output, tokens); output = replaceNewlines(output, options.singleline); - return output; - - // TODO highlight search terms + // TODO markdown - // TODO leave space for markdown + return output; } export function sanitize(text) { @@ -176,9 +175,45 @@ function stripHashtags(text, tokens) { return prefix + alias; } - output = output.replace(/(^|\W)(#[a-zA-Z0-9.\-_]+)\b/g, stripHashtag); + return output.replace(/(^|\W)(#[a-zA-Z0-9.\-_]+)\b/g, stripHashtag); +} + +function highlightSearchTerm(text, tokens, searchTerm) { + let output = text; - return output; + var newTokens = new Map(); + for (let [alias, token] of tokens) { + if (token.originalText === searchTerm) { + const index = newTokens.size; + const newAlias = `SEARCH_TERM${index}`; + + newTokens.set(newAlias, { + value: `${alias}`, + originalText: token.originalText + }); + + output = output.replace(alias, newAlias); + } + } + + // the new tokens are stashed in a separate map since we can't add objects to a map during iteration + for (let newToken of newTokens) { + tokens.set(newToken[0], newToken[1]); + } + + function replaceSearchTerm(fullMatch, prefix, word) { + const index = tokens.size; + const alias = `SEARCH_TERM${index}`; + + tokens.set(alias, { + value: `${word}`, + originalText: word + }); + + return prefix + alias; + } + + return output.replace(new RegExp(`(^|\\W)(${searchTerm})\b`, 'gi'), replaceSearchTerm); } function replaceTokens(text, tokens) { -- cgit v1.2.3-1-g7c22