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 } from '~/models/resource';
14 import { GroupClass } from '~/models/group';
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, SearchBarAdvanceFormData } from '~/models/search-bar';
19 import { debounce } from 'debounce';
20 import * as _ from "lodash";
21 import { getModifiedKeysValues } from "~/common/objects";
22 import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
23 import { Session } from "~/models/session";
24 import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions";
25 import { ListResults } from "~/services/common-service/common-service";
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));
180 debounceStartSearch(dispatch);
182 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
183 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
184 dispatch(searchBarActions.SELECT_FIRST_ITEM());
188 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
189 (dispatch: Dispatch, getState: () => RootState) => {
190 event.preventDefault();
191 const searchValue = getState().searchBar.searchValue;
192 dispatch<any>(saveRecentQuery(searchValue));
193 dispatch<any>(loadRecentQueries());
194 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
195 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
196 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
197 dispatch(searchResultsPanelActions.CLEAR());
198 dispatch(navigateToSearchResults);
201 const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
203 const startSearch = () =>
204 (dispatch: Dispatch, getState: () => RootState) => {
205 const searchValue = getState().searchBar.searchValue;
206 dispatch<any>(searchData(searchValue));
209 const searchGroups = (searchValue: string, limit: number) =>
210 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
211 const currentView = getState().searchBar.currentView;
213 if (searchValue || currentView === SearchView.ADVANCED) {
214 const sq = parseSearchQuery(searchValue);
215 const clusterId = getSearchQueryFirstProp(sq, 'cluster');
216 const sessions = getSearchSessions(clusterId, getState().auth.sessions);
217 const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
218 const filters = getFilters('name', searchValue, sq);
219 return services.groupsService.contents('', {
226 const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
227 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
231 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
232 let value = data.searchValue;
234 const addRem = (field: string, key: string) => {
237 if (data.hasOwnProperty(key)) {
238 const pattern = v === false
239 ? `${field.replace(':', '\\:\\s*')}\\s*`
240 : `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
241 value = value.replace(new RegExp(pattern), '');
245 const nv = v === true
249 if (mode === 'rebuild') {
250 value = value + ' ' + nv;
252 value = nv + ' ' + value;
257 keyMap.forEach(km => addRem(km[0], km[1]));
262 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
265 const flatData = (data: SearchBarAdvanceFormData) => {
267 searchValue: data.searchValue,
269 cluster: data.cluster,
270 projectUuid: data.projectUuid,
271 inTrash: data.inTrash,
272 dateFrom: data.dateFrom,
275 (data.properties || []).forEach(p => fo[`prop-${p.key}`] = p.value);
281 ['cluster', 'cluster'],
282 ['project', 'projectUuid'],
283 ['is:trashed', 'inTrash'],
284 ['from', 'dateFrom'],
287 _.union(data.properties, prevData ? prevData.properties : [])
288 .forEach(p => keyMap.push([`has:${p.key}`, `prop-${p.key}`]));
291 const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
292 value = buildQueryFromKeyMap({
293 searchValue: data.searchValue,
295 } as SearchBarAdvanceFormData, keyMap, "reuse");
297 value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
300 value = value.trim();
304 export class ParseSearchQuery {
305 hasKeywords: boolean;
308 [key: string]: string[]
312 export const parseSearchQuery: (query: string) => ParseSearchQuery = (searchValue: string) => {
323 const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + (search.includes(keyword) ? 1 : 0), 0);
326 const properties = {};
328 keywords.forEach(k => {
329 let p = searchValue.indexOf(k);
330 const key = k.substr(0, k.length - 1);
333 const l = searchValue.length;
337 let i = p + k.length;
338 while (i < l && searchValue[i] === ' ') {
342 while (i < l && searchValue[i] !== ' ') {
347 if (hasKeywords(v)) {
348 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
351 if (!properties[key]) {
352 properties[key] = [];
354 properties[key].push(v);
356 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
358 p = searchValue.indexOf(k);
362 const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
364 return { hasKeywords: keywordsCnt > 0, values, properties };
367 export const getSearchQueryFirstProp = (sq: ParseSearchQuery, name: string) => sq.properties[name] && sq.properties[name][0];
368 export const getSearchQueryPropValue = (sq: ParseSearchQuery, name: string, value: string) => sq.properties[name] && sq.properties[name].find((v: string) => v === value);
369 export const getSearchQueryProperties = (sq: ParseSearchQuery): PropertyValue[] => {
370 if (sq.properties.has) {
371 return sq.properties.has.map((value: string) => {
372 const v = value.split(':');
382 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
383 const sq = parseSearchQuery(query);
386 searchValue: sq.values.join(' '),
387 type: getSearchQueryFirstProp(sq, 'type') as ResourceKind,
388 cluster: getSearchQueryFirstProp(sq, 'cluster'),
389 projectUuid: getSearchQueryFirstProp(sq, 'project'),
390 inTrash: getSearchQueryPropValue(sq, 'is', 'trashed') !== undefined,
391 dateFrom: getSearchQueryFirstProp(sq, 'from'),
392 dateTo: getSearchQueryFirstProp(sq, 'to'),
393 properties: getSearchQueryProperties(sq),
399 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
400 return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
403 export const getFilters = (filterName: string, searchValue: string, sq: ParseSearchQuery): string => {
404 const filter = new FilterBuilder();
406 const resourceKind = getSearchQueryFirstProp(sq, 'type') as ResourceKind;
409 switch (resourceKind) {
410 case ResourceKind.COLLECTION:
411 prefix = GroupContentsResourcePrefix.COLLECTION;
413 case ResourceKind.PROCESS:
414 prefix = GroupContentsResourcePrefix.PROCESS;
417 prefix = GroupContentsResourcePrefix.PROJECT;
421 const isTrashed = getSearchQueryPropValue(sq, 'is', 'trashed');
423 if (!sq.hasKeywords) {
425 .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
426 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
427 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS);
430 filter.addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS);
434 sq.values.forEach(v =>
435 filter.addILike(filterName, v, prefix)
438 sq.values.forEach(v => {
440 .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
441 .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
444 filter.addILike(filterName, v, GroupContentsResourcePrefix.PROCESS);
450 filter.addEqual("is_trashed", true);
453 const projectUuid = getSearchQueryFirstProp(sq, 'project');
455 filter.addEqual('uuid', projectUuid, prefix);
458 const dateFrom = getSearchQueryFirstProp(sq, 'from');
460 filter.addGte('modified_at', buildDateFilter(dateFrom));
463 const dateTo = getSearchQueryFirstProp(sq, 'to');
465 filter.addLte('modified_at', buildDateFilter(dateTo));
468 const props = getSearchQueryProperties(sq);
471 filter.addILike(`properties.${p.key}`, p.value);
473 filter.addExists(p.key);
478 .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
479 .addIsA("uuid", buildUuidFilter(resourceKind))
483 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
484 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
487 const buildDateFilter = (date?: string): string => {
488 return date ? date : '';
491 export const initAdvanceFormProjectsTree = () =>
492 (dispatch: Dispatch) => {
493 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
496 export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
497 (dispatch: Dispatch) => {
498 dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
501 export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
502 (dispatch: Dispatch) => {
503 dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
506 export const moveUp = () =>
507 (dispatch: Dispatch) => {
508 dispatch(searchBarActions.MOVE_UP());
511 export const moveDown = () =>
512 (dispatch: Dispatch) => {
513 dispatch(searchBarActions.MOVE_DOWN());