1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { ofType, unionize, UnionOf } from "~/common/unionize";
6 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
7 import { Dispatch } from 'redux';
8 import { arrayPush, change, initialize } from 'redux-form';
9 import { RootState } from '~/store/store';
10 import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions';
11 import { ServiceRepository } from '~/services/services';
12 import { FilterBuilder } from "~/services/api/filter-builder";
13 import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource';
14 import { SearchView } from '~/store/search-bar/search-bar-reducer';
15 import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
16 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
17 import { PropertyValue, SearchBarAdvanceFormData } from '~/models/search-bar';
18 import * as _ from "lodash";
19 import { getModifiedKeysValues } from "~/common/objects";
20 import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
21 import { Session } from "~/models/session";
22 import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions";
23 import { ListResults } from "~/services/common-service/common-service";
24 import * as parser from './search-query/arv-parser';
25 import { Keywords } from './search-query/arv-parser';
27 export const searchBarActions = unionize({
28 SET_CURRENT_VIEW: ofType<string>(),
29 OPEN_SEARCH_VIEW: ofType<{}>(),
30 CLOSE_SEARCH_VIEW: ofType<{}>(),
31 SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
32 SET_SEARCH_VALUE: ofType<string>(),
33 SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
34 SET_RECENT_QUERIES: ofType<string[]>(),
35 UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
36 SET_SELECTED_ITEM: ofType<string>(),
37 MOVE_UP: ofType<{}>(),
38 MOVE_DOWN: ofType<{}>(),
39 SELECT_FIRST_ITEM: ofType<{}>()
42 export type SearchBarActions = UnionOf<typeof searchBarActions>;
44 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
46 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
48 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
50 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
52 export const saveRecentQuery = (query: string) =>
53 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
54 services.searchService.saveRecentQuery(query);
57 export const loadRecentQueries = () =>
58 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
59 const recentQueries = services.searchService.getRecentQueries();
60 dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
64 export const searchData = (searchValue: string) =>
65 async (dispatch: Dispatch, getState: () => RootState) => {
66 const currentView = getState().searchBar.currentView;
67 dispatch(searchResultsPanelActions.CLEAR());
68 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
69 if (searchValue.length > 0) {
70 dispatch<any>(searchGroups(searchValue, 5));
71 if (currentView === SearchView.BASIC) {
72 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
73 dispatch(navigateToSearchResults);
78 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
79 async (dispatch: Dispatch) => {
80 dispatch<any>(saveQuery(data));
81 dispatch(searchResultsPanelActions.CLEAR());
82 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
83 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
84 dispatch(navigateToSearchResults);
87 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
88 (dispatch: Dispatch, getState: () => RootState) => {
89 const searchValue = getState().searchBar.searchValue;
90 const value = getQueryFromAdvancedData({
94 dispatch(searchBarActions.SET_SEARCH_VALUE(value));
97 export const setAdvancedDataFromSearchValue = (search: string) =>
98 async (dispatch: Dispatch) => {
99 const data = getAdvancedDataFromQuery(search);
100 dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
101 if (data.projectUuid) {
102 await dispatch<any>(activateSearchBarProject(data.projectUuid));
103 dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
107 const saveQuery = (data: SearchBarAdvanceFormData) =>
108 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
109 const savedQueries = services.searchService.getSavedQueries();
110 if (data.saveQuery && data.queryName) {
111 const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
112 data.searchValue = getState().searchBar.searchValue;
114 services.searchService.editSavedQueries(data);
115 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
116 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
118 services.searchService.saveQuery(data);
119 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
120 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
125 export const deleteSavedQuery = (id: number) =>
126 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
127 services.searchService.deleteSavedQuery(id);
128 const savedSearchQueries = services.searchService.getSavedQueries();
129 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
130 return savedSearchQueries || [];
133 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
134 (dispatch: Dispatch<any>) => {
135 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
136 dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
137 dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
140 export const openSearchView = () =>
141 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
142 const savedSearchQueries = services.searchService.getSavedQueries();
143 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
144 dispatch(loadRecentQueries());
145 dispatch(searchBarActions.OPEN_SEARCH_VIEW());
146 dispatch(searchBarActions.SELECT_FIRST_ITEM());
149 export const closeSearchView = () =>
150 (dispatch: Dispatch<any>) => {
151 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
152 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
155 export const closeAdvanceView = () =>
156 (dispatch: Dispatch<any>) => {
157 dispatch(searchBarActions.SET_SEARCH_VALUE(''));
158 dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
159 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
162 export const navigateToItem = (uuid: string) =>
163 (dispatch: Dispatch<any>) => {
164 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
165 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
166 dispatch(navigateTo(uuid));
169 export const changeData = (searchValue: string) =>
170 (dispatch: Dispatch, getState: () => RootState) => {
171 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
172 const currentView = getState().searchBar.currentView;
173 const searchValuePresent = searchValue.length > 0;
175 if (currentView === SearchView.ADVANCED) {
176 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
177 } else if (searchValuePresent) {
178 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
179 dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
181 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
182 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
183 dispatch(searchBarActions.SELECT_FIRST_ITEM());
187 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
188 (dispatch: Dispatch, getState: () => RootState) => {
189 event.preventDefault();
190 const searchValue = getState().searchBar.searchValue;
191 dispatch<any>(saveRecentQuery(searchValue));
192 dispatch<any>(loadRecentQueries());
193 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
194 if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
195 dispatch<any>(navigateTo(searchValue));
197 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
198 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
199 dispatch(searchResultsPanelActions.CLEAR());
200 dispatch(navigateToSearchResults);
205 const startSearch = () =>
206 (dispatch: Dispatch, getState: () => RootState) => {
207 const searchValue = getState().searchBar.searchValue;
208 dispatch<any>(searchData(searchValue));
211 const searchGroups = (searchValue: string, limit: number) =>
212 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
213 const currentView = getState().searchBar.currentView;
215 if (searchValue || currentView === SearchView.ADVANCED) {
216 const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
217 const sessions = getSearchSessions(clusterId, getState().auth.sessions);
218 const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
219 const filters = queryToFilters(searchValue);
220 return services.groupsService.contents('', {
227 const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
228 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
232 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
233 let value = data.searchValue;
235 const addRem = (field: string, key: string) => {
238 if (data.hasOwnProperty(key)) {
239 const pattern = v === false
240 ? `${field.replace(':', '\\:\\s*')}\\s*`
241 : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
242 value = value.replace(new RegExp(pattern), '');
246 const nv = v === true
250 if (mode === 'rebuild') {
251 value = value + ' ' + nv;
253 value = nv + ' ' + value;
258 keyMap.forEach(km => addRem(km[0], km[1]));
263 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
266 const flatData = (data: SearchBarAdvanceFormData) => {
268 searchValue: data.searchValue,
270 cluster: data.cluster,
271 projectUuid: data.projectUuid,
272 inTrash: data.inTrash,
273 dateFrom: data.dateFrom,
276 (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
282 ['cluster', 'cluster'],
283 ['project', 'projectUuid'],
284 [`is:${parser.States.TRASHED}`, 'inTrash'],
285 ['from', 'dateFrom'],
288 _.union(data.properties, prevData ? prevData.properties : [])
289 .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
292 const fd = flatData(data);
293 const pfd = flatData(prevData);
294 const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
295 value = buildQueryFromKeyMap({
296 searchValue: data.searchValue,
298 } as SearchBarAdvanceFormData, keyMap, "reuse");
300 value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
303 value = value.trim();
307 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
308 const { tokens, searchString } = parser.parseSearchQuery(query);
309 const getValue = parser.getValue(tokens);
311 searchValue: searchString,
312 type: getValue(Keywords.TYPE) as ResourceKind,
313 cluster: getValue(Keywords.CLUSTER),
314 projectUuid: getValue(Keywords.PROJECT),
315 inTrash: parser.isTrashed(tokens),
316 dateFrom: getValue(Keywords.FROM) || '',
317 dateTo: getValue(Keywords.TO) || '',
318 properties: parser.getProperties(tokens),
324 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
325 return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
328 export const queryToFilters = (query: string) => {
329 const data = getAdvancedDataFromQuery(query);
330 const filter = new FilterBuilder();
331 const resourceKind = data.type;
333 if (data.searchValue) {
334 filter.addFullTextSearch(data.searchValue);
337 if (data.projectUuid) {
338 filter.addEqual('ownerUuid', data.projectUuid);
342 filter.addGte('modified_at', buildDateFilter(data.dateFrom));
346 filter.addLte('modified_at', buildDateFilter(data.dateTo));
349 data.properties.forEach(p => {
352 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
353 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
355 filter.addExists(p.key);
359 .addIsA("uuid", buildUuidFilter(resourceKind))
363 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
364 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
367 const buildDateFilter = (date?: string): string => {
368 return date ? date : '';
371 export const initAdvanceFormProjectsTree = () =>
372 (dispatch: Dispatch) => {
373 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
376 export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
377 (dispatch: Dispatch) => {
378 dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
381 export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
382 (dispatch: Dispatch) => {
383 dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
386 export const moveUp = () =>
387 (dispatch: Dispatch) => {
388 dispatch(searchBarActions.MOVE_UP());
391 export const moveDown = () =>
392 (dispatch: Dispatch) => {
393 dispatch(searchBarActions.MOVE_DOWN());