aboutsummaryrefslogtreecommitdiffstats
path: root/background_scripts
diff options
context:
space:
mode:
authorPhil Crosby2012-06-03 16:45:09 -0700
committerPhil Crosby2012-06-03 16:56:39 -0700
commit79fc51ab7ba61ef836f5a208dbf3a4c1dcdb4c53 (patch)
tree2d2d0e03cae1e711f1aa2cb808f945a69fb7d6f2 /background_scripts
parent98e9e8ca04918de3fae369e1f3b0285ba17d4188 (diff)
downloadvimium-79fc51ab7ba61ef836f5a208dbf3a4c1dcdb4c53.tar.bz2
Fix a highlighting bug where we overlapping query terms would corrupt the html
Diffstat (limited to 'background_scripts')
-rw-r--r--background_scripts/completion.coffee34
1 files changed, 24 insertions, 10 deletions
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 <span>.
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) +
- "<span class='match'>" + string.substr(i, length) + "</span>" +
- string.substr(i + length)
+ string.substring(0, start) +
+ "<span class='match'>" + string.substring(start, end) + "</span>" +
+ string.substring(end)
string
# Creates a Regexp from the given string, with all special Regexp characters escaped.