mirror of
https://github.com/flarum/framework.git
synced 2025-05-22 14:49:57 +08:00
Massive JavaScript cleanup
- Use JSX for templates - Docblock/comment everything - Mostly passes ESLint (still some work to do) - Lots of renaming, refactoring, etc. CSS hasn't been updated yet.
This commit is contained in:
@ -1,21 +1,37 @@
|
||||
import truncate from '../utils/truncate';
|
||||
import { truncate } from 'flarum/utils/string';
|
||||
|
||||
export default function(string, phrase, length) {
|
||||
if (!phrase) {
|
||||
return string;
|
||||
}
|
||||
/**
|
||||
* The `highlight` helper searches for a word phrase in a string, and wraps
|
||||
* matches with the <mark> tag.
|
||||
*
|
||||
* @param {String} string The string to highlight.
|
||||
* @param {String|RegExp} phrase The word or words to highlight.
|
||||
* @param {Integer} [length] The number of characters to truncate the string to.
|
||||
* The string will be truncated surrounding the first match.
|
||||
* @return {Object}
|
||||
*/
|
||||
export default function highlight(string, phrase, length) {
|
||||
if (!phrase && !length) return string;
|
||||
|
||||
// Convert the word phrase into a global regular expression (if it isn't
|
||||
// already) so we can search the string for matched.
|
||||
const regexp = phrase instanceof RegExp ? phrase : new RegExp(phrase, 'gi');
|
||||
|
||||
let highlightedString = string;
|
||||
let highlighted = string;
|
||||
let start = 0;
|
||||
|
||||
// If a length was given, the truncate the string surrounding the first match.
|
||||
if (length) {
|
||||
start = Math.max(0, string.search(regexp) - length / 2);
|
||||
highlightedString = truncate(highlightedString, length, start);
|
||||
if (phrase) start = Math.max(0, string.search(regexp) - length / 2);
|
||||
|
||||
highlighted = truncate(highlighted, length, start);
|
||||
}
|
||||
|
||||
highlightedString = $('<div/>').text(highlightedString).html().replace(regexp, '<mark>$&</mark>');
|
||||
// Convert the string into HTML entities, then highlight all matches with
|
||||
// <mark> tags. Then we will return the result as a trusted HTML string.
|
||||
highlighted = $('<div/>').text(highlighted).html();
|
||||
|
||||
return m.trust(highlightedString);
|
||||
if (phrase) highlighted = highlighted.replace(regexp, '<mark>$&</mark>');
|
||||
|
||||
return m.trust(highlighted);
|
||||
}
|
||||
|
Reference in New Issue
Block a user