]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/header/highlight.pipe.ts
Fix upload avatar button
[github/Chocobozzz/PeerTube.git] / client / src / app / header / highlight.pipe.ts
CommitLineData
f409f0c3
RK
1import { PipeTransform, Pipe } from '@angular/core'
2import { SafeHtml } from '@angular/platform-browser'
3
4// Thanks https://gist.github.com/adamrecsko/0f28f474eca63e0279455476cc11eca7#gistcomment-2917369
5@Pipe({ name: 'highlight' })
6export class HighlightPipe implements PipeTransform {
7 /* use this for single match search */
9b8a7aa8 8 static SINGLE_MATCH = 'Single-Match'
f409f0c3 9 /* use this for single match search with a restriction that target should start with search string */
9b8a7aa8 10 static SINGLE_AND_STARTS_WITH_MATCH = 'Single-And-StartsWith-Match'
f409f0c3 11 /* use this for global search */
9b8a7aa8 12 static MULTI_MATCH = 'Multi-Match'
f409f0c3 13
9b8a7aa8 14 transform (
5fb2e288
C
15 contentString: string = null,
16 stringToHighlight: string = null,
17 option = 'Single-And-StartsWith-Match',
18 caseSensitive = false,
19 highlightStyleName = 'search-highlight'
f409f0c3 20 ): SafeHtml {
9b8a7aa8
RK
21 if (stringToHighlight && contentString && option) {
22 let regex: any = ''
23 const caseFlag: string = !caseSensitive ? 'i' : ''
5fb2e288 24
9b8a7aa8
RK
25 switch (option) {
26 case 'Single-Match': {
27 regex = new RegExp(stringToHighlight, caseFlag)
28 break
29 }
30 case 'Single-And-StartsWith-Match': {
8a979d73 31 regex = new RegExp('^' + stringToHighlight, caseFlag)
9b8a7aa8
RK
32 break
33 }
34 case 'Multi-Match': {
35 regex = new RegExp(stringToHighlight, 'g' + caseFlag)
36 break
37 }
38 default: {
39 // default will be a global case-insensitive match
40 regex = new RegExp(stringToHighlight, 'gi')
41 }
f409f0c3 42 }
5fb2e288 43
9b8a7aa8 44 const replaced = contentString.replace(
5fb2e288
C
45 regex,
46 (match) => `<span class="${highlightStyleName}">${match}</span>`
9b8a7aa8 47 )
5fb2e288 48
9b8a7aa8
RK
49 return replaced
50 } else {
51 return contentString
52 }
f409f0c3
RK
53 }
54}