openaire-library/searchPages/searchUtils/highlight/highlight.component.ts

71 lines
2.0 KiB
TypeScript

import {Component, Input, OnInit} from "@angular/core";
import {StringUtils} from "../../../utils/string-utils.class";
import {Organization, Project} from "../../../utils/entities/searchResult";
export interface Keyword {
field: string,
value: string,
tokenized: boolean
}
@Component({
selector: 'highlight',
template: `
<ng-template [ngIf]="html" [ngIfElse]="highlightText">
<ng-container *ngFor="let token of split()">
<span [class.uk-text-bold]="isHighlighted(token)" [innerHTML]="token"></span>
</ng-container>
</ng-template>
<ng-template #highlightText>
<ng-container *ngFor="let token of split()">
<span *ngIf="isHighlighted(token) else noHighlight" class="uk-text-bold">{{token}}</span>
<ng-template #noHighlight>{{token}}</ng-template>
</ng-container>
</ng-template>`
})
export class HighlightComponent implements OnInit{
@Input() keywords: Keyword[];
@Input() field: string;
@Input() element: string | Project[] | Organization[];
@Input() html = false;
public text: string;
public separators: string[] = [' ', '-', ',', '.'];
constructor() {
}
ngOnInit(): void {
if(typeof this.element === "string") {
this.text = this.element;
} else {
/*if(this.element instanceof Project) {
this.text = this.element.
}*/
}
}
public split(): string[] {
return StringUtils.split(this.text, this.separators);
}
/**
* Returns true if the word given is matched with any keyword
*
* @param word
*/
isHighlighted(word: string) {
if (this.keywords) {
for (let keyword of this.keywords) {
if (!keyword.field || keyword.field === this.field) {
if (keyword.tokenized && keyword.value.toLowerCase() === word.toLowerCase()) {
return true;
} else if (!keyword.tokenized && word.toLowerCase().includes(keyword.value.toLowerCase())) {
return true;
}
}
}
}
return false;
}
}