Skip to content

Commit

Permalink
fix(text-search): fix endless while loop
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielhase committed Sep 9, 2021
1 parent ac9193c commit ad5e433
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
8 changes: 8 additions & 0 deletions spec/highlighting.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ describe('Highlighting', function () {
expect(firstMatch.startIndex).to.equal(5)
expect(firstMatch.endIndex).to.equal(10)
})

it('does not go into an endless loop without a marker node', function () {
const blockText = 'Mehr als 90 Prozent der Fälle in Grossbritannien in den letzten vier Wochen gehen auf die Delta-Variante zurück. Anders als bei vorangegangenen Wellen scheinen sich jedoch die Fallzahlen von den Todesfällen und Hospitalisierungen zu entkoppeln.'
const text = ''
const textSearch = new WordHighlighter(null, 'text')
const matches = textSearch.findMatches(blockText, [text])
expect(matches).to.equal(undefined)
})
})

describe('highlightSupport', function () {
Expand Down
22 changes: 16 additions & 6 deletions src/plugins/highlighting/text-highlighting.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,22 @@ export default class WordHighlighting {
this.matchMode = matchMode
}

isElement (obj) {
try {
// Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement
} catch (e) {
// Browsers not supporting W3 DOM2 don't have HTMLElement and
// an exception is thrown and we end up here. Testing some
// properties that all elements have (works on IE7)
return (typeof obj === 'object') &&
(obj.nodeType === 1) && (typeof obj.style === 'object') &&
(typeof obj.ownerDocument === 'object')
}
}

findMatches (text, highlights) {
if (!text) return
if (!text || text === '' || !this.isElement(this.marker)) return

if (highlights && highlights.length > 0) {
return this.searchMatches(text, highlights)
Expand All @@ -21,11 +35,7 @@ export default class WordHighlighting {
: createHighlightRegex

const regex = createRegex(highlights)
const matches = []
let match
while ((match = regex.exec(text))) {
matches.push(match)
}
const matches = [...text.matchAll(regex)]

return matches.map((entry) => this.prepareMatch(entry))
}
Expand Down

0 comments on commit ad5e433

Please sign in to comment.