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 } from '~/store/tree-picker/tree-picker-actions';
11 import { ServiceRepository } from '~/services/services';
12 import { FilterBuilder } from "~/services/api/filter-builder";
13 import { getResourceKind, 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 { getClusterObjectType, PropertyValues, SearchBarAdvanceFormData } from '~/models/search-bar';
19 import { debounce } from 'debounce';
20 import * as _ from "lodash";
21 import { getModifiedKeysValues } from "~/common/objects";
23 export const searchBarActions = unionize({
24 SET_CURRENT_VIEW: ofType<string>(),
25 OPEN_SEARCH_VIEW: ofType<{}>(),
26 CLOSE_SEARCH_VIEW: ofType<{}>(),
27 SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
28 SET_SEARCH_VALUE: ofType<string>(),
29 SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
30 SET_RECENT_QUERIES: ofType<string[]>(),
31 UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
32 SET_SELECTED_ITEM: ofType<string>(),
33 MOVE_UP: ofType<{}>(),
34 MOVE_DOWN: ofType<{}>(),
35 SELECT_FIRST_ITEM: ofType<{}>()
38 export type SearchBarActions = UnionOf<typeof searchBarActions>;
40 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
42 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
44 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
46 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
48 export const saveRecentQuery = (query: string) =>
49 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
50 services.searchService.saveRecentQuery(query);
53 export const loadRecentQueries = () =>
54 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
55 const recentQueries = services.searchService.getRecentQueries();
56 dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
60 export const searchData = (searchValue: string) =>
61 async (dispatch: Dispatch, getState: () => RootState) => {
62 const currentView = getState().searchBar.currentView;
63 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
64 if (searchValue.length > 0) {
65 dispatch<any>(searchGroups(searchValue, 5));
66 if (currentView === SearchView.BASIC) {
67 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
68 dispatch(navigateToSearchResults);
73 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
74 async (dispatch: Dispatch) => {
75 dispatch<any>(saveQuery(data));
76 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
77 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
78 dispatch(navigateToSearchResults);
81 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
82 (dispatch: Dispatch, getState: () => RootState) => {
83 const searchValue = getState().searchBar.searchValue;
84 const value = getQueryFromAdvancedData({
88 dispatch(searchBarActions.SET_SEARCH_VALUE(value));
91 export const setAdvancedDataFromSearchValue = (search: string) =>
92 (dispatch: Dispatch) => {
93 const data = getAdvancedDataFromQuery(search);
94 dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
97 const saveQuery = (data: SearchBarAdvanceFormData) =>
98 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
99 const savedQueries = services.searchService.getSavedQueries();
100 if (data.saveQuery && data.queryName) {
101 const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
102 data.searchValue = getState().searchBar.searchValue;
104 services.searchService.editSavedQueries(data);
105 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
106 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
108 services.searchService.saveQuery(data);
109 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
110 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
115 export const deleteSavedQuery = (id: number) =>
116 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
117 services.searchService.deleteSavedQuery(id);
118 const savedSearchQueries = services.searchService.getSavedQueries();
119 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
120 return savedSearchQueries || [];
123 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
124 (dispatch: Dispatch<any>) => {
125 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
126 dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
127 dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
130 export const openSearchView = () =>
131 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
132 const savedSearchQueries = services.searchService.getSavedQueries();
133 dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
134 dispatch(loadRecentQueries());
135 dispatch(searchBarActions.OPEN_SEARCH_VIEW());
136 dispatch(searchBarActions.SELECT_FIRST_ITEM());
139 export const closeSearchView = () =>
140 (dispatch: Dispatch<any>) => {
141 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
142 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
145 export const closeAdvanceView = () =>
146 (dispatch: Dispatch<any>) => {
147 dispatch(searchBarActions.SET_SEARCH_VALUE(''));
148 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
151 export const navigateToItem = (uuid: string) =>
152 (dispatch: Dispatch<any>) => {
153 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
154 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
155 dispatch(navigateTo(uuid));
158 export const changeData = (searchValue: string) =>
159 (dispatch: Dispatch, getState: () => RootState) => {
160 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
161 const currentView = getState().searchBar.currentView;
162 const searchValuePresent = searchValue.length > 0;
164 if (currentView === SearchView.ADVANCED) {
165 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
166 } else if (searchValuePresent) {
167 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
168 dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
169 debounceStartSearch(dispatch);
171 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
172 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
173 dispatch(searchBarActions.SELECT_FIRST_ITEM());
177 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
178 (dispatch: Dispatch, getState: () => RootState) => {
179 event.preventDefault();
180 const searchValue = getState().searchBar.searchValue;
181 dispatch<any>(saveRecentQuery(searchValue));
182 dispatch<any>(loadRecentQueries());
183 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
184 dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
185 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
186 dispatch(navigateToSearchResults);
189 const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
191 const startSearch = () =>
192 (dispatch: Dispatch, getState: () => RootState) => {
193 const searchValue = getState().searchBar.searchValue;
194 dispatch<any>(searchData(searchValue));
197 const searchGroups = (searchValue: string, limit: number) =>
198 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
199 const currentView = getState().searchBar.currentView;
201 if (searchValue || currentView === SearchView.ADVANCED) {
202 const filters = getFilters('name', searchValue);
203 const { items } = await services.groupsService.contents('', {
208 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
212 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
213 let value = data.searchValue;
215 const rem = (field: string, fieldValue: any, value: string) => {
218 const addRem = (field: string, key: string) => {
221 if (data.hasOwnProperty(key)) {
222 const pattern = v === false
223 ? `${field.replace(':', '\\:\\s*')}\\s*`
224 : `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
225 value = value.replace(new RegExp(pattern), '');
229 const nv = v === true
233 if (mode === 'rebuild') {
234 value = value + ' ' + nv;
236 value = nv + ' ' + value;
241 keyMap.forEach(km => addRem(km[0], km[1]));
246 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
249 const flatData = (data: SearchBarAdvanceFormData) => {
251 searchValue: data.searchValue,
253 cluster: data.cluster,
254 projectUuid: data.projectUuid,
255 inTrash: data.inTrash,
256 dateFrom: data.dateFrom,
259 (data.properties || []).forEach(p => fo[`prop-${p.key}`] = p.value);
265 ['cluster', 'cluster'],
266 ['project', 'projectUuid'],
267 ['is:trashed', 'inTrash'],
268 ['from', 'dateFrom'],
271 _.union(data.properties, prevData ? prevData.properties : [])
272 .forEach(p => keyMap.push([`has:${p.key}`, `prop-${p.key}`]));
275 const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
276 value = buildQueryFromKeyMap({
277 searchValue: data.searchValue,
279 } as SearchBarAdvanceFormData, keyMap, "reuse");
281 value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
284 value = value.trim();
288 export const parseQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string) => {
299 const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
302 const properties = {};
304 keywords.forEach(k => {
305 let p = searchValue.indexOf(k);
306 const key = k.substr(0, k.length - 1);
309 const l = searchValue.length;
313 let i = p + k.length;
314 while (i < l && searchValue[i] === ' ') {
318 while (i < l && searchValue[i] !== ' ') {
323 if (hasKeywords(v)) {
324 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
327 if (!properties[key]) {
328 properties[key] = [];
330 properties[key].push(v);
332 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
334 p = searchValue.indexOf(k);
338 const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
340 return { hasKeywords: keywordsCnt > 0, values, properties };
343 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
344 const r = parseQuery(query);
346 const getFirstProp = (name: string) => r.properties[name] && r.properties[name][0];
347 const getPropValue = (name: string, value: string) => r.properties[name] && r.properties[name].find((v: string) => v === value);
348 const getProperties = () => {
349 if (r.properties.has) {
350 return r.properties.has.map((value: string) => {
351 const v = value.split(':');
362 searchValue: r.values.join(' '),
363 type: getResourceKind(getFirstProp('type')),
364 cluster: getClusterObjectType(getFirstProp('cluster')),
365 projectUuid: getFirstProp('project'),
366 inTrash: getPropValue('is', 'trashed') !== undefined,
367 dateFrom: getFirstProp('from'),
368 dateTo: getFirstProp('to'),
369 properties: getProperties(),
375 export const getFilters = (filterName: string, searchValue: string): string => {
376 const filter = new FilterBuilder();
378 const pq = parseQuery(searchValue);
380 if (!pq.hasKeywords) {
382 .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
383 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
384 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
387 if (pq.properties.type) {
388 pq.values.forEach(v => {
390 switch (ResourceKind[pq.properties.type]) {
391 case ResourceKind.PROJECT:
392 prefix = GroupContentsResourcePrefix.PROJECT;
394 case ResourceKind.COLLECTION:
395 prefix = GroupContentsResourcePrefix.COLLECTION;
397 case ResourceKind.PROCESS:
398 prefix = GroupContentsResourcePrefix.PROCESS;
402 filter.addILike(filterName, v, prefix);
406 pq.values.forEach(v => {
408 .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
409 .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
410 .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
414 if (pq.properties.is && pq.properties.is === 'trashed') {
417 if (pq.properties.project) {
418 filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
421 if (pq.properties.from) {
422 filter.addGte('modified_at', buildDateFilter(pq.properties.from));
425 if (pq.properties.to) {
426 filter.addLte('modified_at', buildDateFilter(pq.properties.to));
429 // .addIsA("uuid", buildUuidFilter(resourceKind))
430 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
431 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
432 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
433 // .addLte('modified_at', buildDateFilter(dateTo))
434 // .addGte('modified_at', buildDateFilter(dateFrom))
435 // .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
439 .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
443 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
444 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
447 const buildDateFilter = (date?: string): string => {
448 return date ? date : '';
451 export const initAdvanceFormProjectsTree = () =>
452 (dispatch: Dispatch) => {
453 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
456 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
457 (dispatch: Dispatch) => {
458 dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
461 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
462 (dispatch: Dispatch) => {
463 dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
466 export const moveUp = () =>
467 (dispatch: Dispatch) => {
468 dispatch(searchBarActions.MOVE_UP());
471 export const moveDown = () =>
472 (dispatch: Dispatch) => {
473 dispatch(searchBarActions.MOVE_DOWN());