-
Notifications
You must be signed in to change notification settings - Fork 334
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improvement: Use existing match highlighter for search matches.
- Loading branch information
Showing
4 changed files
with
70 additions
and
58 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { escapeRegexModifiers, escapeHtmlEntities } from './helpers' | ||
|
||
/** | ||
* Returns an HTML string highlighting the individual tokens from the query string. | ||
*/ | ||
export function highlightMatches (text, query, opts = {}) { | ||
// Sort terms length, so that the longest are highlighted first. | ||
if (typeof query === 'string') { | ||
query = query.split(/\s+/) | ||
} | ||
const terms = query.sort((term1, term2) => term2.length - term1.length) | ||
return highlightTerms(text, terms, opts) | ||
} | ||
|
||
function highlightTerms (text, terms, opts) { | ||
if (terms.length === 0) return text | ||
|
||
let flags = 'i' | ||
|
||
if (opts.multiline) { | ||
flags = 'is' | ||
} | ||
|
||
const [firstTerm, ...otherTerms] = terms | ||
const match = text.match(new RegExp(`(.*)(${escapeRegexModifiers(firstTerm)})(.*)`, flags)) | ||
|
||
if (match) { | ||
const [, before, matching, after] = match | ||
// Note: this has exponential complexity, but we expect just a few terms, so that's fine. | ||
return highlightTerms(before, terms, opts) + '<em>' + escapeHtmlEntities(matching) + '</em>' + highlightTerms(after, terms, opts) | ||
} else { | ||
return highlightTerms(text, otherTerms, opts) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.