1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import axios from "axios";
6 import { ofType, unionize, UnionOf } from "common/unionize";
7 import { GroupContentsResource, GroupContentsResourcePrefix } from 'services/groups-service/groups-service';
8 import { Dispatch } from 'redux';
9 import { change, initialize, untouch } from 'redux-form';
10 import { RootState } from 'store/store';
11 import { initUserProject, treePickerActions } from 'store/tree-picker/tree-picker-actions';
12 import { ServiceRepository } from 'services/services';
13 import { FilterBuilder } from "services/api/filter-builder";
14 import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from 'models/resource';
15 import { SearchView } from 'store/search-bar/search-bar-reducer';
16 import { navigateTo, navigateToSearchResults } from 'store/navigation/navigation-action';
17 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
18 import { PropertyValue, SearchBarAdvancedFormData } from 'models/search-bar';
19 import { union } from "lodash";
20 import { getModifiedKeysValues } from "common/objects";
21 import { activateSearchBarProject } from "store/search-bar/search-bar-tree-actions";
22 import { Session } from "models/session";
23 import { searchResultsPanelActions } from "store/search-results-panel/search-results-panel-actions";
24 import { ListResults } from "services/common-service/common-service";
25 import * as parser from './search-query/arv-parser';
26 import { Keywords } from './search-query/arv-parser';
27 import { Vocabulary, getTagKeyLabel, getTagValueLabel } from "models/vocabulary";
29 export const searchBarActions = unionize({
30 SET_CURRENT_VIEW: ofType<string>(),
31 OPEN_SEARCH_VIEW: ofType<{}>(),
32 CLOSE_SEARCH_VIEW: ofType<{}>(),
33 SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
34 SET_SEARCH_VALUE: ofType<string>(),
35 SET_SAVED_QUERIES: ofType<SearchBarAdvancedFormData[]>(),
36 SET_RECENT_QUERIES: ofType<string[]>(),
37 UPDATE_SAVED_QUERY: ofType<SearchBarAdvancedFormData[]>(),
38 SET_SELECTED_ITEM: ofType<string>(),
39 MOVE_UP: ofType<{}>(),
40 MOVE_DOWN: ofType<{}>(),
41 SELECT_FIRST_ITEM: ofType<{}>(),
42 SET_SEARCH_OFFSETS: ofType<Record<string, number>>(),
45 export type SearchBarActions = UnionOf<typeof searchBarActions>;
47 export const SEARCH_BAR_ADVANCED_FORM_NAME = 'searchBarAdvancedFormName';
49 export const SEARCH_BAR_ADVANCED_FORM_PICKER_ID = 'searchBarAdvancedFormPickerId';
51 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
53 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
55 export const saveRecentQuery = (query: string) =>
56 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
57 services.searchService.saveRecentQuery(query);
60 export const loadRecentQueries = () =>
61 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
62 const recentQueries = services.searchService.getRecentQueries();
63 dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
67 export const searchData = (searchValue: string, useCancel = false) =>
68 async (dispatch: Dispatch, getState: () => RootState) => {
69 const currentView = getState().searchBar.currentView;
70 dispatch(searchResultsPanelActions.CLEAR());
71 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
72 if (searchValue.length > 0) {
73 dispatch<any>(searchGroups(searchValue, 5, useCancel));
74 if (currentView === SearchView.BASIC) {
75 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
76 dispatch(navigateToSearchResults(searchValue));
81 export const searchAdvancedData = (data: SearchBarAdvancedFormData) =>
82 async (dispatch: Dispatch, getState: () => RootState) => {
83 dispatch<any>(saveQuery(data));
84 const searchValue = getState().searchBar.searchValue;
85 dispatch(searchResultsPanelActions.CLEAR());
86 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
87 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
88 dispatch(navigateToSearchResults(searchValue));
91 export const setSearchValueFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) =>
92 (dispatch: Dispatch, getState: () => RootState) => {
93 if (data.projectObject) {
94 data.projectUuid = data.projectObject.uuid;
96 const searchValue = getState().searchBar.searchValue;
97 const value = getQueryFromAdvancedData({
101 dispatch(searchBarActions.SET_SEARCH_VALUE(value));
104 export const setAdvancedDataFromSearchValue = (search: string, vocabulary: Vocabulary) =>
105 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
106 const data = getAdvancedDataFromQuery(search, vocabulary);
107 if (data.projectUuid) {
108 data.projectObject = await services.projectService.get(data.projectUuid);
110 dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
111 if (data.projectUuid) {
112 await dispatch<any>(activateSearchBarProject(data.projectUuid));
113 dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID, id: data.projectUuid }));
117 const saveQuery = (data: SearchBarAdvancedFormData) =>
118 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
119 const savedQueries = services.searchService.getSavedQueries();
120 if (data.saveQuery && data.queryName) {
121 const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
122 data.searchValue = getState().searchBar.searchValue;
124 services.searchService.editSavedQueries(data);
125 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
126 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
128 services.searchService.saveQuery(data);
129 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
130 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
135 export const deleteSavedQuery = (id: number) =>
136 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
137 services.searchService.deleteSavedQuery(id);
138 const savedSearchQueries = services.searchService.getSavedQueries();
139 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
140 return savedSearchQueries || [];
143 export const editSavedQuery = (data: SearchBarAdvancedFormData) =>
144 (dispatch: Dispatch<any>) => {
145 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
146 dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
147 dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
150 export const openSearchView = () =>
151 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
152 const savedSearchQueries = services.searchService.getSavedQueries();
153 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
154 dispatch(loadRecentQueries());
155 dispatch(searchBarActions.OPEN_SEARCH_VIEW());
156 dispatch(searchBarActions.SELECT_FIRST_ITEM());
159 export const closeSearchView = () =>
160 (dispatch: Dispatch<any>) => {
161 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
162 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
165 export const closeAdvanceView = () =>
166 (dispatch: Dispatch<any>) => {
167 dispatch(searchBarActions.SET_SEARCH_VALUE(''));
168 dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID }));
169 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
172 export const navigateToItem = (uuid: string) =>
173 (dispatch: Dispatch<any>) => {
174 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
175 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
176 dispatch(navigateTo(uuid));
179 export const changeData = (searchValue: string) =>
180 (dispatch: Dispatch, getState: () => RootState) => {
181 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
182 const currentView = getState().searchBar.currentView;
183 const searchValuePresent = searchValue.length > 0;
185 if (currentView === SearchView.ADVANCED) {
186 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
187 } else if (searchValuePresent) {
188 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
189 dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
191 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
192 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
193 dispatch(searchBarActions.SELECT_FIRST_ITEM());
197 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
198 (dispatch: Dispatch, getState: () => RootState) => {
199 event.preventDefault();
200 const searchValue = getState().searchBar.searchValue;
201 dispatch<any>(saveRecentQuery(searchValue));
202 dispatch<any>(loadRecentQueries());
203 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
204 if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
205 dispatch<any>(navigateTo(searchValue));
207 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
208 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
209 dispatch(searchResultsPanelActions.CLEAR());
210 dispatch(navigateToSearchResults(searchValue));
214 let cancelTokens: any[] = [];
215 const searchGroups = (searchValue: string, limit: number, useCancel = false) =>
216 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
217 const currentView = getState().searchBar.currentView;
219 if (cancelTokens.length > 0 && useCancel) {
220 cancelTokens.forEach(cancelToken => (cancelToken as any).cancel('New search request triggered.'));
224 setTimeout(async () => {
225 if (searchValue || currentView === SearchView.ADVANCED) {
226 const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
227 const sessions = getSearchSessions(clusterId, getState().auth.sessions);
228 const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map((session, index) => {
229 cancelTokens.push(axios.CancelToken.source());
230 const filters = queryToFilters(searchValue, session.apiRevision);
231 return services.groupsService.contents('', {
235 }, session, cancelTokens[index].token);
240 const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
242 if (lists.filter(list => !!(list as any).items).length !== lists.length) {
243 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
245 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
251 const buildQueryFromKeyMap = (data: any, keyMap: string[][]) => {
252 let value = data.searchValue;
254 const addRem = (field: string, key: string) => {
256 // Remove previous search expression.
257 if (data.hasOwnProperty(key)) {
260 pattern = `${field.replace(':', '\\:\\s*')}\\s*`;
261 } else if (key.startsWith('prop-')) {
262 // On properties, only remove key:value duplicates, allowing
263 // multiple properties with the same key.
264 const oldValue = key.slice(5).split(':')[1];
265 pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*${oldValue}\\s*`;
267 pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
269 value = value.replace(new RegExp(pattern), '');
271 // Re-add it with the current search value.
273 const nv = v === true
276 // Always append to the end to keep user-entered text at the start.
277 value = value + ' ' + nv;
280 keyMap.forEach(km => addRem(km[0], km[1]));
284 export const getQueryFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => {
287 const flatData = (data: SearchBarAdvancedFormData) => {
289 searchValue: data.searchValue,
291 cluster: data.cluster,
292 projectUuid: data.projectUuid,
293 inTrash: data.inTrash,
294 pastVersions: data.pastVersions,
295 dateFrom: data.dateFrom,
298 (data.properties || []).forEach(p =>
299 fo[`prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] = `"${p.valueID || p.value}"`
306 ['cluster', 'cluster'],
307 ['project', 'projectUuid'],
308 [`is:${parser.States.TRASHED}`, 'inTrash'],
309 [`is:${parser.States.PAST_VERSION}`, 'pastVersions'],
310 ['from', 'dateFrom'],
313 union(data.properties, prevData ? prevData.properties : [])
314 .forEach(p => keyMap.push(
315 [`has:"${p.keyID || p.key}"`, `prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`]
318 const modified = getModifiedKeysValues(flatData(data), prevData ? flatData(prevData) : {});
319 value = buildQueryFromKeyMap(
320 { searchValue: data.searchValue, ...modified } as SearchBarAdvancedFormData, keyMap);
322 value = value.trim();
326 export const getAdvancedDataFromQuery = (query: string, vocabulary?: Vocabulary): SearchBarAdvancedFormData => {
327 const { tokens, searchString } = parser.parseSearchQuery(query);
328 const getValue = parser.getValue(tokens);
330 searchValue: searchString,
331 type: getValue(Keywords.TYPE) as ResourceKind,
332 cluster: getValue(Keywords.CLUSTER),
333 projectUuid: getValue(Keywords.PROJECT),
334 inTrash: parser.isTrashed(tokens),
335 pastVersions: parser.isPastVersion(tokens),
336 dateFrom: getValue(Keywords.FROM) || '',
337 dateTo: getValue(Keywords.TO) || '',
338 properties: vocabulary
339 ? parser.getProperties(tokens).map(
343 key: getTagKeyLabel(p.key, vocabulary),
345 value: getTagValueLabel(p.key, p.value, vocabulary),
348 : parser.getProperties(tokens),
354 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
355 return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
358 export const queryToFilters = (query: string, apiRevision: number) => {
359 const data = getAdvancedDataFromQuery(query);
360 const filter = new FilterBuilder();
361 const resourceKind = data.type;
363 if (data.searchValue) {
364 filter.addFullTextSearch(data.searchValue);
367 if (data.projectUuid) {
368 filter.addEqual('owner_uuid', data.projectUuid);
372 filter.addGte('modified_at', buildDateFilter(data.dateFrom));
376 filter.addLte('modified_at', buildDateFilter(data.dateTo));
379 data.properties.forEach(p => {
381 if (apiRevision < 20200212) {
383 .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
384 .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION)
385 .addEqual(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROCESS);
388 .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
389 .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION)
390 .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROCESS);
393 filter.addExists(p.key);
397 .addIsA("uuid", buildUuidFilter(resourceKind))
401 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
402 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
405 const buildDateFilter = (date?: string): string => {
406 return date ? date : '';
409 export const initAdvancedFormProjectsTree = () =>
410 (dispatch: Dispatch) => {
411 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCED_FORM_PICKER_ID));
414 export const changeAdvancedFormProperty = (propertyField: string, value: PropertyValue[] | string = '') =>
415 (dispatch: Dispatch) => {
416 dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, value));
419 export const resetAdvancedFormProperty = (propertyField: string) =>
420 (dispatch: Dispatch) => {
421 dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, null));
422 dispatch(untouch(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField));
425 export const moveUp = () =>
426 (dispatch: Dispatch) => {
427 dispatch(searchBarActions.MOVE_UP());
430 export const moveDown = () =>
431 (dispatch: Dispatch) => {
432 dispatch(searchBarActions.MOVE_DOWN());
435 export const setSearchOffsets = (sessionId: string, offset: number) => {
436 return (dispatch: Dispatch) => {
437 dispatch(searchBarActions.SET_SEARCH_OFFSETS({id:[sessionId], offset }));