1
0
Fork 0
peertube/client/src/app/header/highlight.pipe.ts

55 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-01-20 14:12:51 +00:00
import { PipeTransform, Pipe } from '@angular/core'
import { SafeHtml } from '@angular/platform-browser'
// Thanks https://gist.github.com/adamrecsko/0f28f474eca63e0279455476cc11eca7#gistcomment-2917369
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
/* use this for single match search */
static SINGLE_MATCH = 'Single-Match'
2020-01-20 14:12:51 +00:00
/* use this for single match search with a restriction that target should start with search string */
static SINGLE_AND_STARTS_WITH_MATCH = 'Single-And-StartsWith-Match'
2020-01-20 14:12:51 +00:00
/* use this for global search */
static MULTI_MATCH = 'Multi-Match'
2020-01-20 14:12:51 +00:00
transform (
2020-05-29 14:16:24 +00:00
contentString: string = null,
stringToHighlight: string = null,
option = 'Single-And-StartsWith-Match',
caseSensitive = false,
highlightStyleName = 'search-highlight'
2020-01-20 14:12:51 +00:00
): SafeHtml {
if (stringToHighlight && contentString && option) {
let regex: any = ''
const caseFlag: string = !caseSensitive ? 'i' : ''
2020-05-29 14:16:24 +00:00
switch (option) {
case 'Single-Match': {
regex = new RegExp(stringToHighlight, caseFlag)
break
}
case 'Single-And-StartsWith-Match': {
2020-02-12 15:20:49 +00:00
regex = new RegExp('^' + stringToHighlight, caseFlag)
break
}
case 'Multi-Match': {
regex = new RegExp(stringToHighlight, 'g' + caseFlag)
break
}
default: {
// default will be a global case-insensitive match
regex = new RegExp(stringToHighlight, 'gi')
}
2020-01-20 14:12:51 +00:00
}
2020-05-29 14:16:24 +00:00
const replaced = contentString.replace(
2020-05-29 14:16:24 +00:00
regex,
(match) => `<span class="${highlightStyleName}">${match}</span>`
)
2020-05-29 14:16:24 +00:00
return replaced
} else {
return contentString
}
2020-01-20 14:12:51 +00:00
}
}