From 79fc51ab7ba61ef836f5a208dbf3a4c1dcdb4c53 Mon Sep 17 00:00:00 2001 From: Phil Crosby Date: Sun, 3 Jun 2012 16:45:09 -0700 Subject: Fix a highlighting bug where we overlapping query terms would corrupt the html --- background_scripts/completion.coffee | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) (limited to 'background_scripts') diff --git a/background_scripts/completion.coffee b/background_scripts/completion.coffee index ca0c6c45..f76b0fe9 100644 --- a/background_scripts/completion.coffee +++ b/background_scripts/completion.coffee @@ -25,23 +25,37 @@ class Suggestion url = url.substring(url, url.length - 1) if url[url.length - 1] == "/" url + # Merges the given list of ranges such that any overlapping regions are combined. E.g. + # mergeRanges([0, 4], [3, 6]) => [0, 6]. A range is [startIndex, endIndex]. + mergeRanges: (ranges) -> + previous = ranges.shift() + mergedRanges = [previous] + ranges.forEach (range) -> + if previous[1] >= range[0] + previous[1] = Math.max(range[1], previous[1]) + else + mergedRanges.push(range) + previous = range + mergedRanges + # Wraps each occurence of the query terms in the given string in a . highlightTerms: (string) -> - toReplace = {} + ranges = [] for term in @queryTerms regexp = @escapeRegexp(term) i = string.search(regexp) - toReplace[i] = term.length if i >= 0 && (!toReplace[i] || toReplace[i].length < term.length) + ranges.push([i, i + term.length]) if i >= 0 + + return string if ranges.length == 0 - indices = [] - indices.push([key, toReplace[key]]) for key of toReplace - indices.sort (a, b) -> b - a - for [i, length] in indices - i = +i # convert i from String to Integer. + ranges = @mergeRanges(ranges.sort (a, b) -> a[0] - b[0]) + # Replace portions of the string from right to left. + ranges = ranges.sort (a, b) -> b[0] - a[0] + for [start, end] in ranges string = - string.substr(0, i) + - "" + string.substr(i, length) + "" + - string.substr(i + length) + string.substring(0, start) + + "" + string.substring(start, end) + "" + + string.substring(end) string # Creates a Regexp from the given string, with all special Regexp characters escaped. -- cgit v1.2.3