Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

mark correct item

ulferts006d2cae9af5
diff --git a/frontend/src/app/modules/global_search/input/global-search-input.component.html b/frontend/src/app/modules/global_search/input/global-search-input.component.html
index 37031a314ce..83ad7760cf7 100644
--- a/frontend/src/app/modules/global_search/input/global-search-input.component.html
+++ b/frontend/src/app/modules/global_search/input/global-search-input.component.html
@@ -12,7 +12,8 @@
id="global-search-input"
placeholder="{{text.search_dots}}"
accesskey="4"
- [ngClass]="'top-menu-search--input'"
+ [ngClass]="{'top-menu-search--input': true, '-markable': markable }"
+ [(ngModel)]="selectedItem"
[class.-expanded]="expanded"
[openOnEnter]="false"
[searchFn]="customSearchFn"
@@ -23,13 +24,13 @@
(search)="search($event)"
(open)="openCloseMenu(currentValue)"
(close)="select.searchTerm = currentValue"
- (change)="onChange($event)"
+ (change)="followSelectedItem()"
(keydown.enter)="onEnterBeforeResultsLoaded()"
(keydown.escape)="blur()"
(clear)="clearSearch()">
<ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
<div *ngIf="!item.id; else workPackageItemTemplate">
- <div tabindex="-1" class="global-search--option">
+ <div tabindex="-1" class="global-search--option"(click)="followItem(item)">
<div class="global-search--option-wrapper">
<span class="global-search--search-term"> {{currentValue}} </span>
<span class="global-search--project-scope" title="{{item.projectScope}}"> {{item.text}} ↵ </span>
@@ -37,9 +38,8 @@
</div>
</div>
<ng-template #workPackageItemTemplate>
- <div tabindex="-1" class="global-search--option">
+ <div tabindex="-1" class="global-search--option" (click)="redirectToWp(item.id, $event)">
<a class="global-search--option-wrapper"
- (click)="redirectToWp(item.id, $event)"
[href]="wpPath(item.id)">
<span class="global-search--wp-id"
title="{{item.status}}"
diff --git a/frontend/src/app/modules/global_search/input/global-search-input.component.sass b/frontend/src/app/modules/global_search/input/global-search-input.component.sass
index 14a7f46ccb6..e38e3408413 100644
--- a/frontend/src/app/modules/global_search/input/global-search-input.component.sass
+++ b/frontend/src/app/modules/global_search/input/global-search-input.component.sass
@@ -75,25 +75,36 @@ $search-input-height: 30px
input
color: var(--header-search-field-font-color)
- .scroll-host
- @include styled-scroll-bar
- max-height: 80vh
- height: auto
-
- .ng-option
- border-bottom: 1px solid #EAEAEA
- white-space: normal
- padding: 5px 10px
- &:last-child
- border-bottom: none
- &.ng-option-marked
- background-color: var(--drop-down-hover-bg-color)
- color: var(--header-drop-down-item-font-hover-color)
- &.ng-option-disabled
- display: none
- &.ng-option-selected
- background-color: var(--drop-down-selected-bg-color)
- color: var(--header-drop-down-item-font-hover-color)
+ .scroll-host
+ @include styled-scroll-bar
+ max-height: 80vh
+ height: auto
+
+ .ng-option
+ border-bottom: 1px solid #EAEAEA
+ white-space: normal
+ padding: 5px 10px
+ // We do not want the default highlighting of ng-select to take place as
+ // it will highlight the element last hovered over/navigated to even
+ // though the selection might have changed in the meantime.
+ // We either want to mark the first element or, in case of a direct hit (by the wp id)
+ // we want to highlight that hit.
+ background-color: unset
+ &:last-child
+ border-bottom: none
+ &.ng-option-marked
+ color: var(--header-drop-down-item-font-hover-color)
+ &.ng-option-disabled
+ display: none
+ &.ng-option-selected
+ color: var(--header-drop-down-item-font-hover-color)
+
+ &.-markable
+ .ng-option
+ &.ng-option-marked
+ background-color: var(--drop-down-hover-bg-color)
+ &.ng-option-selected
+ background-color: var(--drop-down-selected-bg-color)
.global-search--wp-id
color: var(--gray-dark)
diff --git a/frontend/src/app/modules/global_search/input/global-search-input.component.ts b/frontend/src/app/modules/global_search/input/global-search-input.component.ts
index 3afa36808e7..cef79e90cb6 100644
--- a/frontend/src/app/modules/global_search/input/global-search-input.component.ts
+++ b/frontend/src/app/modules/global_search/input/global-search-input.component.ts
@@ -49,7 +49,7 @@ import {DeviceService} from "core-app/modules/common/browser/device.service";
import {NgSelectComponent} from "@ng-select/ng-select";
import {Observable, of} from "rxjs";
import {Highlighting} from "core-components/wp-fast-table/builders/highlighting/highlighting.functions";
-import {map} from "rxjs/internal/operators";
+import {map, tap} from "rxjs/internal/operators";
import {HalResourceNotificationService} from "core-app/modules/hal/services/hal-resource-notification.service";
import {DebouncedRequestSwitchmap, errorNotificationHandler} from "core-app/helpers/rxjs/debounced-input-switchmap";
import {LinkHandling} from "core-app/modules/common/link-handling/link-handling";
@@ -64,6 +64,11 @@ interface SearchResultItem {
$href:string;
}
+interface SearchOptionItem {
+ projectScope:string;
+ text:string;
+}
+
@Component({
selector: globalSearchSelector,
changeDetection: ChangeDetectionStrategy.OnPush,
@@ -77,19 +82,25 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
@ViewChild(NgSelectComponent, { static: true }) public ngSelectComponent:NgSelectComponent;
public expanded:boolean = false;
- public suggestions:any[];
+ public markable = false;
/** Keep a switchmap for search term and loading state */
- public requests = new DebouncedRequestSwitchmap<string, SearchResultItem>(
- (searchTerm:string) => this.autocompleteWorkPackages(searchTerm),
+ public requests = new DebouncedRequestSwitchmap<string, SearchResultItem|SearchOptionItem>(
+ (searchTerm:string) => this.autocompleteWorkPackages(searchTerm).pipe(
+ tap(() => {
+ setTimeout(() => this.setMarkedOption(), 50);
+ })
+ ),
errorNotificationHandler(this.halNotification)
);
/** Remember the current value */
public currentValue:string = '';
- /** Remember if we have found an exact ID match */
- public exactMatchedWpId:string|null = null
+ /** Remember the item that best matches the query.
+ * That way, it will be highlighted (as we manually mark the selected item) and we can handle enter.
+ * */
+ public selectedItem:SearchResultItem|SearchOptionItem|null;
private unregisterGlobalListener:Function|undefined;
@@ -117,7 +128,7 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
// check searchterm on init, expand / collapse search bar and set correct classes
this.ngSelectComponent.searchTerm = this.currentValue = this.globalSearchService.searchTerm;
this.expanded = (this.ngSelectComponent.searchTerm.length > 0);
- jQuery('#top-menu').toggleClass('-global-search-expanded', this.expanded);
+ this.toggleTopMenuClass();
}
ngOnDestroy() {
@@ -147,20 +158,7 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
// open or close mobile search
public toggleMobileSearch() {
this.expanded = !this.expanded;
- jQuery('#top-menu').toggleClass('-global-search-expanded', this.expanded);
- }
-
- // load selected item
- public onChange($event:any) {
- let selectedOption = $event;
- // Clicks on will be handled by other handler
- if (selectedOption.id) {
- window.location.href = this.wpPath(selectedOption.id);
- } else {
- // update embedded table and title when new search is submitted
- this.globalSearchService.searchTerm = this.currentValue;
- this.searchInScope(selectedOption.projectScope);
- }
+ this.toggleTopMenuClass();
}
public redirectToWp(id:string, event:JQuery.TriggeredEvent) {
@@ -190,7 +188,7 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
public onFocus() {
this.expanded = true;
- jQuery('#top-menu').addClass('-global-search-expanded');
+ this.toggleTopMenuClass();
this.openCloseMenu(this.currentValue);
}
@@ -198,7 +196,7 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
if (!this.deviceService.isMobile) {
this.expanded = (this.ngSelectComponent.searchTerm.length > 0);
this.ngSelectComponent.isOpen = false;
- jQuery('#top-menu').toggleClass('-global-search-expanded', this.expanded);
+ this.toggleTopMenuClass();
}
}
@@ -211,11 +209,8 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
public onEnterBeforeResultsLoaded() {
if (!this.requests.hasResults) {
this.searchInScope(this.currentScope);
- return;
- }
-
- if (this.exactMatchedWpId) {
- window.location.href = this.wpPath(this.exactMatchedWpId);
+ } else {
+ this.followSelectedItem();
}
}
@@ -223,68 +218,149 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
return Highlighting.inlineClass('status', statusId);
}
+ private get isDirectHit() {
+ return this.selectedItem && this.selectedItem.hasOwnProperty('id');
+ }
+
+ public followItem(item:SearchResultItem|SearchOptionItem) {
+ if (item.hasOwnProperty('id')) {
+ window.location.href = this.wpPath((item as SearchResultItem).id);
+ } else {
+ // update embedded table and title when new search is submitted
+ this.globalSearchService.searchTerm = this.currentValue;
+ this.searchInScope((item as SearchOptionItem).projectScope);
+ }
+ }
+
+ public followSelectedItem() {
+ if (this.selectedItem) {
+ this.followItem(this.selectedItem);
+ }
+ }
+
// return all project scope items and all items which contain the search term
public customSearchFn(term:string, item:any):boolean {
return item.id === undefined || item.subject.toLowerCase().indexOf(term.toLowerCase()) !== -1;
}
- private autocompleteWorkPackages(query:string):Observable<SearchResultItem[]> {
+ private autocompleteWorkPackages(query:string):Observable<(SearchResultItem|SearchOptionItem)[]> {
if (!query) {
return of([]);
}
- // Remove ID marker # when searching for #<number>
- if (query.match(/^#(\d+)/)) {
- query = query.substr(1);
- }
-
- // Test for exact ID matches
- this.exactMatchedWpId = null;
+ // Reset the currently selected item.
+ // We do not follow the typical goal of an autocompleter of "setting a value" here.
+ this.selectedItem = null;
+ // Hide highlighting of ng-option
+ this.markable = false;
- let href:string = this.PathHelperService.api.v3.wpBySubjectOrId(query);
- this.addSuggestions();
+ let hashFreeQuery = this.queryWithoutHash(query);
- return this.halResourceService
- .get<CollectionResource<WorkPackageResource>>(href)
+ return this.fetchSearchResults(hashFreeQuery, hashFreeQuery !== query)
.pipe(
map((collection) => {
- return this.suggestions.concat(collection.elements.map((wp) => {
- if (query === wp.id!.toString()) {
- this.exactMatchedWpId = query;
- }
-
- return {
- id: wp.id!,
- subject: wp.subject,
- status: wp.status.name,
- statusId: wp.status.idFromLink,
- $href: wp.$href
- };
- }));
+ return this.searchResultsToOptions(collection.elements, hashFreeQuery);
})
);
}
+ // Remove ID marker # when searching for #<number>
+ private queryWithoutHash(query:string) {
+ if (query.match(/^#(\d+)/)) {
+ return query.substr(1);
+ } else {
+ return query;
+ }
+ }
+
+ private fetchSearchResults(query:string, idOnly:boolean) {
+ let href:string = this.PathHelperService.api.v3.wpBySubjectOrId(query, idOnly);
+
+ return this.halResourceService
+ .get<CollectionResource<WorkPackageResource>>(href);
+
+ }
+
+ private searchResultsToOptions(results:WorkPackageResource[], query:string) {
+ let searchItems = results.map((wp) => {
+ let item = {
+ id: wp.id!,
+ subject: wp.subject,
+ status: wp.status.name,
+ statusId: wp.status.idFromLink,
+ $href: wp.$href
+ } as SearchResultItem;
+
+ // If we have a direct hit, we choose it to be the selected element.
+ if (query === wp.id!.toString()) {
+ this.selectedItem = item;
+ }
+
+ return item;
+ });
+
+ let searchOptions = this.detailedSearchOptions();
+
+ if (!this.selectedItem) {
+ this.selectedItem = searchOptions[0];
+ }
+
+ return (searchOptions as (SearchResultItem|SearchOptionItem)[]).concat(searchItems);
+ }
+
// set the possible 'search in scope' options for the current project path
- private addSuggestions() {
- this.suggestions = [];
+ private detailedSearchOptions() {
+ let searchOptions = [];
// add all options when searching within a project
// otherwise search in 'all projects'
if (this.currentProjectService.path) {
- this.suggestions.push('current_project_and_all_descendants');
- this.suggestions.push('current_project');
+ searchOptions.push('current_project_and_all_descendants');
+ searchOptions.push('current_project');
}
if (this.globalSearchService.projectScope === 'current_project') {
- this.suggestions.reverse();
+ searchOptions.reverse();
}
- this.suggestions.push('all_projects');
+ searchOptions.push('all_projects');
- this.suggestions = this.suggestions.map((suggestion:string) => {
+ return searchOptions.map((suggestion:string) => {
return { projectScope: suggestion, text: this.text[suggestion] };
});
}
+ /*
+ * Set the marked ng-option within ng-select and apply the class to highlight marked options.
+ *
+ * ng-select differentiates between the selected and the marked option. The selected optinon is the option
+ * that is binded via ng-model. The marked option is the one that the user is currently selecting (via mouse or keyboard up/down).
+ * When hitting enter, the marked option is taken to be the new selected option. Ng-select will retain the index of the marked
+ * option between individual searches. The selected option has no influence on the marked option. This is problematic
+ * in our use case as the user might have:
+ * * the mouse hovering (deliberately or not) over the search options which will mark that option.
+ * * marked an option for a previous search but might then have decided to add/remove additional characters to the search.
+ *
+ * In both cases, whenever the user presses enter then, ng-select assigns the marked option to the ng-model.
+ *
+ * Our goal however is to either:
+ * * mark the direct hit (id matches) if it available
+ * * mark the first item if there is no direct hit
+ *
+ * And we need to update the marked option after every search.
+ *
+ * There is no way of doing this via the interface provided in the template. There is only [markFirst] and it neither allows us
+ * to mark a direct hit, nor does it reset after a search. We handle this then by selecting the desired element once the
+ * search results are back. We then set the marked option to be the selected option.
+ *
+ * In order to avoid flickering, a -markable modifyer class is unset/set before/after searching. This will unset the background until we
+ * have marked the element we wish to.
+ */
+ private setMarkedOption() {
+ this.markable = true;
+ this.ngSelectComponent.itemsList.markItem(this.ngSelectComponent.itemsList.selectedItems[0]);
+
+ this.cdRef.detectChanges();
+ }
+
private searchInScope(scope:string) {
switch (scope) {
case 'all_projects': {
@@ -345,6 +421,10 @@ export class GlobalSearchInputComponent implements OnInit, OnDestroy {
this.unregisterGlobalListener = undefined;
}
}
+
+ private toggleTopMenuClass() {
+ jQuery('#top-menu').toggleClass('-global-search-expanded', this.expanded);
+ }
}
diff --git a/spec/features/search_spec.rb b/spec/features/search_spec.rb
index 01f86fd0f63..261733f46e1 100644
--- a/spec/features/search_spec.rb
+++ b/spec/features/search_spec.rb
@@ -75,6 +75,8 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
end
end
+ let(:global_search) { ::Components::GlobalSearch.new }
+
let(:query) { 'Subject' }
let(:params) { [project, { q: query }] }
@@ -100,49 +102,66 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
let!(:other_work_package) { FactoryBot.create(:work_package, subject: 'Other work package', project: project) }
it 'provides suggestions' do
- suggestions = search_autocomplete(page.find('.top-menu-search--input'),
- query: query)
+ global_search.search(query, submit: false)
+
# Suggestions shall show latest WPs first.
- expect(suggestions).to have_text('No. 11 WP', wait: 10)
+ global_search.expect_work_package_option(work_packages[11])
# and show maximum 10 suggestions.
- expect(suggestions).to_not have_text('No. 1 WP')
+ global_search.expect_work_package_option(work_packages[2])
+ global_search.expect_no_work_package_option(work_packages[1])
# and unrelated work packages shall not get suggested
- expect(suggestions).to_not have_text(other_work_package.subject)
+ global_search.expect_no_work_package_option(other_work_package)
target_work_package = work_packages.last
+ # If no direct match is available, the first option is marked
+ global_search.expect_in_project_and_subproject_scope_marked
+
# Expect redirection when WP is selected from results
- select_autocomplete(page.find('.top-menu-search--input'),
- query: target_work_package.subject,
- select_text: "##{target_work_package.id}")
+ global_search.search(target_work_package.subject, submit: false)
- sleep 1
+ # Even though there is a work package named the same, we did not search by id
+ # and thus the work package is not selected.
+ global_search.expect_in_project_and_subproject_scope_marked
+
+ # But we can open it by clicking
+ global_search.click_work_package(target_work_package)
+
+ expect(page)
+ .to have_selector('.subject', text: target_work_package.subject)
expect(current_path).to eql project_work_package_path(target_work_package.project, target_work_package, state: 'activity')
first_wp = work_packages.first
# Typing a work package id shall find that work package
- suggestions = search_autocomplete(page.find('.top-menu-search--input'),
- query: first_wp.id.to_s)
- expect(suggestions).to have_text('No. 1 WP', wait: 10)
+ global_search.search(first_wp.id.to_s, submit: false)
+
+ # And it shall be marked as the direct hit.
+ global_search.expect_work_package_marked(first_wp)
+
+ # And the direct hit is opened when enter is pressed
+ global_search.submit_with_enter
+
+ expect(page)
+ .to have_selector('.subject', text: first_wp.subject)
+
+ expect(current_path).to eql project_work_package_path(first_wp.project, first_wp, state: 'activity')
# Typing a hash sign before an ID shall only suggest that work package and (no hits within the subject)
- suggestions = search_autocomplete(page.find('.top-menu-search--input'),
- query: "##{first_wp.id}")
- expect(suggestions).to have_text("Subject", count: 1)
+ global_search.search("##{first_wp.id}", submit: false)
+
+ global_search.expect_work_package_marked(first_wp)
# Expect to have 3 project scope selecting menu entries
- expect(suggestions).to have_text('In this project ↵')
- expect(suggestions).to have_text('In this project + subprojects ↵')
- expect(suggestions).to have_text('In all projects ↵')
+ global_search.expect_scope('In this project ↵')
+ global_search.expect_scope('In this project + subprojects ↵')
+ global_search.expect_scope('In all projects ↵')
# Selection project scope 'In all projects' redirects away from current project.
- select_autocomplete(page.find('.top-menu-search--input'),
- query: query,
- select_text: "In all projects ↵")
+ global_search.submit_in_global_scope
expect(current_path).to match(/\/search/)
- expect(current_url).to match(/\/search\?q=#{query}&work_packages=1&scope=all$/)
+ expect(current_url).to match(/\/search\?q=#{"%23#{first_wp.id}"}&work_packages=1&scope=all$/)
end
end
@@ -197,7 +216,6 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
let(:filters) { ::Components::WorkPackages::Filters.new }
let(:columns) { ::Components::WorkPackages::Columns.new }
let(:top_menu) { ::Components::Projects::TopMenu.new }
- let(:global_search) { ::Components::GlobalSearch.new }
it 'shows a work package table with correct results' do
# Search without subprojects
@@ -254,7 +272,7 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
expect(global_search.input.value).to eq query
# Expect that a fresh global search will reset the advanced filters, i.e. that they are closed
- global_search.search work_packages[6].subject, submit_with_enter: true
+ global_search.search work_packages[6].subject, submit: true
expect(page).to have_text "Search for \"#{work_packages[6].subject}\" in #{project.name}"
@@ -268,7 +286,7 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
# Expect that changing the search term without using the autocompleter will leave the project scope unchanged
# at current_project.
- global_search.search other_work_package.subject, submit_with_enter: true
+ global_search.search other_work_package.subject, submit: true
expect(page).to have_text "Search for \"#{other_work_package.subject}\" in #{project.name}"
@@ -279,11 +297,11 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
# Expect to find custom field values
# ...for type: text
- global_search.search custom_field_text_value, submit_with_enter: true
+ global_search.search custom_field_text_value, submit: true
table.ensure_work_package_not_listed! work_packages[1]
table.expect_work_package_subject(work_packages[0].subject)
# ... for type: string
- global_search.search custom_field_string_value, submit_with_enter: true
+ global_search.search custom_field_string_value, submit: true
table.ensure_work_package_not_listed! work_packages[0]
table.expect_work_package_subject(work_packages[1].subject)
@@ -361,7 +379,6 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
let(:wp_2) { FactoryBot.create :work_package, subject: "Foo # Bar", project: project }
let(:wp_3) { FactoryBot.create :work_package, subject: "Foo &# Bar", project: project }
let!(:work_packages) { [wp_1, wp_2, wp_3] }
- let(:global_search) { ::Components::GlobalSearch.new }
let(:table) { Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container')) }
let(:run_visit) { false }
@@ -375,6 +392,7 @@ describe 'Search', type: :feature, js: true, with_settings: { per_page_options:
# Bug in ng-select causes highlights to break up entities
global_search.find_option "Foo &amp;&amp; Bar"
global_search.find_option "Foo &amp;# Bar"
+ global_search.expect_global_scope_marked
global_search.submit_in_global_scope
table.ensure_work_package_not_listed! wp_2
diff --git a/spec/support/components/global_search.rb b/spec/support/components/global_search.rb
index 6263652da04..0d8fa1547cc 100644
--- a/spec/support/components/global_search.rb
+++ b/spec/support/components/global_search.rb
@@ -17,17 +17,21 @@ module Components
container.find 'input'
end
- def search(query, submit_with_enter: false)
+ def search(query, submit: false)
input.set ''
input.hover
input.click
input.set query
- if submit_with_enter
- input.send_keys :enter
+ if submit
+ submit_with_enter
end
end
+ def submit_with_enter
+ input.send_keys :enter
+ end
+
def expect_open
expect(page).to have_selector(container)
end
@@ -44,6 +48,40 @@ module Components
page.find('.global-search--project-scope[title="all_projects"]', wait: 10).click
end
+ def expect_global_scope_marked
+ expect(page)
+ .to have_selector('.global-search--project-scope[title="all_projects"]', wait: 10)
+ end
+
+ def expect_in_project_and_subproject_scope_marked
+ expect(page)
+ .to have_selector('.global-search--project-scope[title="current_project_and_all_descendants"]', wait: 10)
+ end
+
+ def expect_scope(text)
+ expect(page)
+ .to have_selector('.global-search--project-scope', text: text, wait: 10)
+ end
+
+ def expect_work_package_marked(wp)
+ expect(page)
+ .to have_selector('.ng-option-marked', text: "##{wp.id} #{wp.subject}", wait: 10)
+ end
+
+ def expect_work_package_option(wp)
+ expect(page)
+ .to have_selector('.global-search--option', text: "##{wp.id} #{wp.subject}", wait: 10)
+ end
+
+ def expect_no_work_package_option(wp)
+ expect(page)
+ .not_to have_selector('.global-search--option', text: "##{wp.id} #{wp.subject}")
+ end
+
+ def click_work_package(wp)
+ find_work_package(wp).click
+ end
+
def find_work_package(wp)
find_option "##{wp.id} #{wp.subject}"
end