From f409f0c3b91d85c66b4841d72ea65b5fbe1483d8 Mon Sep 17 00:00:00 2001 From: Rigel Kent Date: Mon, 20 Jan 2020 15:12:51 +0100 Subject: Search typeahead initial design --- client/src/app/shared/angular/highlight.pipe.ts | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 client/src/app/shared/angular/highlight.pipe.ts (limited to 'client/src/app/shared/angular') diff --git a/client/src/app/shared/angular/highlight.pipe.ts b/client/src/app/shared/angular/highlight.pipe.ts new file mode 100644 index 000000000..4199d833e --- /dev/null +++ b/client/src/app/shared/angular/highlight.pipe.ts @@ -0,0 +1,52 @@ +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: string = "Single-Match" + /* use this for single match search with a restriction that target should start with search string */ + static SINGLE_AND_STARTS_WITH_MATCH: string = "Single-And-StartsWith-Match" + /* use this for global search */ + static MULTI_MATCH: string = "Multi-Match" + + constructor() {} + transform( + contentString: string = null, + stringToHighlight: string = null, + option: string = "Single-And-StartsWith-Match", + caseSensitive: boolean = false, + highlightStyleName: string = "search-highlight" + ): SafeHtml { + if (stringToHighlight && contentString && option) { + let regex: any = "" + let caseFlag: string = !caseSensitive ? "i" : "" + switch (option) { + case "Single-Match": { + regex = new RegExp(stringToHighlight, caseFlag) + break + } + case "Single-And-StartsWith-Match": { + 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") + } + } + const replaced = contentString.replace( + regex, + (match) => `${match}` + ) + return replaced + } else { + return contentString + } + } +} -- cgit v1.2.3