Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(search): fix weird behaving in search bar #456

Merged
merged 6 commits into from
Jun 27, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 77 additions & 14 deletions src/app/core/ui/search/search.component.html
Original file line number Diff line number Diff line change
@@ -1,26 +1,89 @@
<div fxHide.xs="true" fxHide="false">
<mat-form-field fxFill class="search-field">
<span matPrefix><mat-icon class="search-icon" fontIcon="fa-search"></mat-icon>&nbsp;</span>
<input matInput (input)="search()" title="Search" [matAutocomplete]="autoResults" [(ngModel)]="searchText">
<div class="desktop-search-bar" fxHide.xs="true" fxHide="false">
<mat-form-field fxFill class="search-field" floatLabel="never">
<span matPrefix>
<mat-icon matPrefix class="search-icon" fontIcon="fa-search"></mat-icon>
</span>
<mat-label>Search</mat-label>
<input
matInput
title="Search"
[matAutocomplete]="autoResults"
[(ngModel)]="searchText"
(ngModelChange)="searchInputChanged($event)"
#searchInput
/>
</mat-form-field>

<mat-autocomplete #autoResults="matAutocomplete" (optionSelected)="clickOption($event.option)">
<mat-option *ngFor="let res of results" [value]="''">
<app-child-block *ngIf="res.getType()==='Child'" [entity]="res" [ngClass]="{'result-inactive': !res.isActive()}"></app-child-block>
<app-school-block *ngIf="res.getType()==='School'" [entity]="res"></app-school-block>
<mat-autocomplete
#autoResults="matAutocomplete"
(optionSelected)="clickOption($event.option)"
>
<mat-option
*ngIf="
searchInput.value.length > 0 &&
searchInput.value.length < MIN_CHARACTERS_FOR_SEARCH
"
>
<p>Insert at least {{ MIN_CHARACTERS_FOR_SEARCH }} characters</p>
sleidig marked this conversation as resolved.
Show resolved Hide resolved
</mat-option>

<mat-option
*ngIf="
results.length === 0 &&
searchInput.value.length >= MIN_CHARACTERS_FOR_SEARCH &&
!isSearching
"
>
<p>There were no results</p>
</mat-option>

<mat-option *ngIf="isSearching">
<p>Search in progress...</p>
</mat-option>

<mat-option *ngFor="let res of results" [value]="">
<app-child-block
*ngIf="res.getType() === 'Child'"
[entity]="res"
[ngClass]="{ 'result-inactive': !res.isActive() }"
></app-child-block>
<app-school-block
*ngIf="res.getType() === 'School'"
[entity]="res"
></app-school-block>
</mat-option>
</mat-autocomplete>
</div>

<button mat-icon-button fxHide.xs="false" fxHide="true" (click)="toggleSearchToolbar()">
<button
mat-icon-button
fxHide.xs="false"
fxHide="true"
(click)="toggleSearchToolbar()"
>
<mat-icon class="header-icon" fontIcon="fa-search"></mat-icon>
</button>

<mat-toolbar *ngIf="showSearchToolbar" class="search-header mat-elevation-z7 mat-typography">
<mat-toolbar
*ngIf="showSearchToolbar"
class="search-header mat-elevation-z7 mat-typography"
>
<mat-toolbar-row fxLayout="row">
<span matPrefix><mat-icon class="search-icon" fontIcon="fa-search"></mat-icon>&nbsp;</span>
<input #searchInput fxFlex="grow" matInput (input)="search()" title="Search" [matAutocomplete]="autoResults" [(ngModel)]="searchText">
{{searchInput.focus()}}
<button mat-icon-button (click)="toggleSearchToolbar()"><mat-icon class="search-icon" fontIcon="fa-times"></mat-icon></button>
<span matPrefix>
<mat-icon class="search-icon" fontIcon="fa-search"></mat-icon>
</span>
<input
#searchInput
fxFlex="grow"
matInput
title="Search"
[matAutocomplete]="autoResults"
[(ngModel)]="searchText"
(ngModelChange)="searchInputChanged($event)"
/>
{{ searchInput.focus() }}
<button mat-icon-button (click)="toggleSearchToolbar()">
<mat-icon class="search-icon" fontIcon="fa-times"></mat-icon>
</button>
</mat-toolbar-row>
</mat-toolbar>
8 changes: 8 additions & 0 deletions src/app/core/ui/search/search.component.scss
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@

.search-field {
color: white;

span {
margin-right: 6px;
}
}

.result-inactive {
color: grey;
}

.desktop-search-bar {
font-size: 16px;
}

.search-header {
position: fixed;
background: white;
Expand Down
35 changes: 27 additions & 8 deletions src/app/core/ui/search/search.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,28 @@ describe("SearchComponent", () => {
expect(mockDatabase.saveDatabaseIndex).toHaveBeenCalled();
});

it("should not search for less than MIN_CHARACTERS_FOR_SEARCH character of input", async () => {
let result = await component.startSearch("A");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).not.toHaveBeenCalled();
expect(component.results).toEqual([]);

result = await component.startSearch("AB");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).not.toHaveBeenCalled();
expect(component.results).toEqual([]);
});

it("should not search for less than one real character of input", async () => {
component.searchText = " ";
await component.search();
const result = await component.startSearch(" ");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).not.toHaveBeenCalled();
expect(component.results).toEqual([]);
});

it("should reset results if a a null search is performed", async () => {
const result = await component.startSearch(null);
component.handleSearchQueryResult(result);
expect(mockDatabase.query).not.toHaveBeenCalled();
expect(component.results).toEqual([]);
});
Expand All @@ -81,8 +100,8 @@ describe("SearchComponent", () => {
};
mockDatabase.query.and.returnValue(Promise.resolve(mockQueryResults));

component.searchText = "A";
await component.search();
const result = await component.startSearch("Ada");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).toHaveBeenCalled();
expect(component.results).toEqual([child1, school1]);
});
Expand All @@ -99,8 +118,8 @@ describe("SearchComponent", () => {
};
mockDatabase.query.and.returnValue(Promise.resolve(mockQueryResults));

component.searchText = "A";
await component.search();
const result = await component.startSearch("Ada");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).toHaveBeenCalled();
expect(component.results.length).toBe(1);
expect(component.results).toEqual([child1]);
Expand All @@ -120,8 +139,8 @@ describe("SearchComponent", () => {
};
mockDatabase.query.and.returnValue(Promise.resolve(mockQueryResults));

component.searchText = "A X";
await component.search();
const result = await component.startSearch("A X");
component.handleSearchQueryResult(result);
expect(mockDatabase.query).toHaveBeenCalled();
expect(component.results).toEqual([child1]);
});
Expand Down
135 changes: 98 additions & 37 deletions src/app/core/ui/search/search.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Child } from "../../../child-dev-project/children/model/child";
import { School } from "../../../child-dev-project/schools/model/school";
import { Entity } from "../../entity/entity";
import { EntitySchemaService } from "../../entity/schema/entity-schema.service";
import { Subject } from "rxjs";
import { debounceTime, switchMap } from "rxjs/operators";

/**
* General search box that provides results out of any kind of entities from the system
Expand All @@ -20,6 +22,13 @@ export class SearchComponent implements OnInit {
results = [];
searchText = "";
showSearchToolbar = false;
isSearching: boolean = false;

MIN_CHARACTERS_FOR_SEARCH: number = 3;
INPUT_DEBOUNCE_TIME_MS: number = 400;

searchStringChanged: Subject<string> = new Subject<string>();
searchQuery: Subject<Promise<any>> = new Subject<Promise<any>>();

constructor(
private db: Database,
Expand All @@ -28,9 +37,91 @@ export class SearchComponent implements OnInit {

ngOnInit() {
this.createSearchIndex();

this.searchStringChanged
.pipe(debounceTime(this.INPUT_DEBOUNCE_TIME_MS))
.subscribe((searchString) => {
this.searchQuery.next(this.startSearch(searchString));
});

this.searchQuery
.pipe(
switchMap((value) => {
return value;
})
)
.subscribe(
(result: { queryResults: any; searchTerms: string[] }) => {
this.handleSearchQueryResult(result);
},
(error) => {
console.error("SearchQuery failed", error);
sleidig marked this conversation as resolved.
Show resolved Hide resolved
}
);
}

async startSearch(searchString: string): Promise<any> {
this.isSearching = true;
this.results = [];

if (!searchString) {
return Promise.resolve();
}

searchString = searchString.toLowerCase();

if (!this.isRelevantSearchInput(searchString)) {
return Promise.resolve();
}

const searchTerms = searchString.split(" ");

const queryResults = await this.db.query("search_index/by_name", {
startkey: searchTerms[0],
endkey: searchTerms[0] + "\ufff0",
include_docs: true,
});

return {
queryResults,
searchTerms,
};
}

private createSearchIndex() {
clickOption(optionElement) {
// simulate a click on the EntityBlock inside the selected option element
optionElement._element.nativeElement.children["0"].children["0"].click();
if (this.showSearchToolbar === true) {
this.showSearchToolbar = false;
}
}

toggleSearchToolbar() {
this.showSearchToolbar = !this.showSearchToolbar;
}

searchInputChanged(searchString) {
this.searchStringChanged.next(searchString);
sleidig marked this conversation as resolved.
Show resolved Hide resolved
}

handleSearchQueryResult(result: {
queryResults: any;
searchTerms: string[];
}) {
this.isSearching = false;

if (!result || !result.queryResults) {
this.results = [];
return;
}

this.results = this.prepareResults(
result.queryResults.rows,
result.searchTerms
);
}

private createSearchIndex(): Promise<any> {
// `emit(x)` to add x as a key to the index that can be searched
const searchMapFunction =
"(doc) => {" +
Expand All @@ -46,28 +137,7 @@ export class SearchComponent implements OnInit {
},
};

this.db.saveDatabaseIndex(designDoc);
}

async search() {
this.searchText = this.searchText.toLowerCase();
if (!this.isRelevantSearchInput(this.searchText)) {
this.results = [];
return;
}

const searchHash = JSON.stringify(this.searchText);
const searchTerms = this.searchText.split(" ");
const queryResults = await this.db.query("search_index/by_name", {
startkey: searchTerms[0],
endkey: searchTerms[0] + "\ufff0",
include_docs: true,
});

if (JSON.stringify(this.searchText) === searchHash) {
// only set result if the user hasn't continued typing and changed the search term already
this.results = this.prepareResults(queryResults.rows, searchTerms);
}
return this.db.saveDatabaseIndex(designDoc);
}

/**
Expand All @@ -77,10 +147,13 @@ export class SearchComponent implements OnInit {
*/
private isRelevantSearchInput(searchText: string) {
const regexp = new RegExp("[a-z]+|[0-9]+");
return this.searchText.match(regexp);
return (
searchText.match(regexp) &&
searchText.length >= this.MIN_CHARACTERS_FOR_SEARCH
);
}

private prepareResults(rows, searchTerms: string[]) {
private prepareResults(rows, searchTerms: string[]): any[] {
return this.getResultsWithoutDuplicates(rows)
.map((doc) => this.transformDocToEntity(doc))
.filter((r) => r !== null)
Expand Down Expand Up @@ -150,16 +223,4 @@ export class SearchComponent implements OnInit {

return t[0].localeCompare(t[1]);
}

clickOption(optionElement) {
// simulate a click on the EntityBlock inside the selected option element
optionElement._element.nativeElement.children["0"].children["0"].click();
if (this.showSearchToolbar === true) {
this.showSearchToolbar = false;
}
}

toggleSearchToolbar() {
this.showSearchToolbar = !this.showSearchToolbar;
}
}
4 changes: 4 additions & 0 deletions src/app/core/ui/ui/ui.component.scss
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,7 @@ body {
padding: 10px;
width: 220px;
}

app-search {
max-height: 100%;
}