From 0791d740a634a70cb8ffb7f762f1a31353560209 Mon Sep 17 00:00:00 2001 From: Sam Date: Thu, 20 Jul 2017 12:26:46 -0400 Subject: [PATCH] FIX: only highlight exact word matches in results - also fixes phrase highlighting --- .../discourse/components/highlight-text.js.es6 | 8 +++----- .../javascripts/discourse/lib/highlight-text.js.es6 | 8 ++++++++ .../discourse/widgets/search-menu-results.js.es6 | 7 ++----- 3 files changed, 13 insertions(+), 10 deletions(-) create mode 100644 app/assets/javascripts/discourse/lib/highlight-text.js.es6 diff --git a/app/assets/javascripts/discourse/components/highlight-text.js.es6 b/app/assets/javascripts/discourse/components/highlight-text.js.es6 index ca783a23b76..a86d2dd3894 100644 --- a/app/assets/javascripts/discourse/components/highlight-text.js.es6 +++ b/app/assets/javascripts/discourse/components/highlight-text.js.es6 @@ -1,13 +1,11 @@ +import highlightText from 'discourse/lib/highlight-text'; + export default Ember.Component.extend({ tagName: 'span', _highlightOnInsert: function() { const term = this.get('highlight'); - const self = this; - - if(!_.isEmpty(term)) { - self.$().highlight(term.split(/\s+/), {className: 'search-highlight'}); - } + highlightText(this.$(), term); }.observes('highlight').on('didInsertElement') }); diff --git a/app/assets/javascripts/discourse/lib/highlight-text.js.es6 b/app/assets/javascripts/discourse/lib/highlight-text.js.es6 new file mode 100644 index 00000000000..6d4b6020c7d --- /dev/null +++ b/app/assets/javascripts/discourse/lib/highlight-text.js.es6 @@ -0,0 +1,8 @@ +export default function($elem, term) { + if(!_.isEmpty(term)) { + // special case ignore "l" which is used for magic sorting + let words = _.reject(term.match(/"[^"]+"|[^\s]+/g), t => t === 'l'); + words = words.map(w => w.replace(/^"(.*)"$/, "$1")); + $elem.highlight(words, {className: 'search-highlight', wordsOnly: true}); + } +} diff --git a/app/assets/javascripts/discourse/widgets/search-menu-results.js.es6 b/app/assets/javascripts/discourse/widgets/search-menu-results.js.es6 index 1e2a6a12451..d210b2e2d99 100644 --- a/app/assets/javascripts/discourse/widgets/search-menu-results.js.es6 +++ b/app/assets/javascripts/discourse/widgets/search-menu-results.js.es6 @@ -4,6 +4,7 @@ import RawHtml from 'discourse/widgets/raw-html'; import { createWidget } from 'discourse/widgets/widget'; import { h } from 'virtual-dom'; import { iconNode } from 'discourse/helpers/fa-icon-node'; +import highlightText from 'discourse/lib/highlight-text'; class Highlighted extends RawHtml { constructor(html, term) { @@ -12,11 +13,7 @@ class Highlighted extends RawHtml { } decorate($html) { - if (this.term) { - // special case ignore "l" which is used for magic sorting - const words = _.reject(this.term.split(/\s+/), t => t === 'l'); - $html.highlight(words, { className: 'search-highlight' }); - } + highlightText($html, this.term); } }