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 interface ParsedSearchQuery {
289 hasKeywords: boolean;
292 [key: string]: string
296 export const parseSearchQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string): ParsedSearchQuery => {
307 const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
310 const properties = {};
312 keywords.forEach(k => {
313 let p = searchValue.indexOf(k);
314 const key = k.substr(0, k.length - 1);
317 const l = searchValue.length;
321 let i = p + k.length;
322 while (i < l && searchValue[i] === ' ') {
326 while (i < l && searchValue[i] !== ' ') {
331 if (hasKeywords(v)) {
332 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
335 if (!properties[key]) {
336 properties[key] = [];
338 properties[key].push(v);
340 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
342 p = searchValue.indexOf(k);
346 const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
348 return { hasKeywords: keywordsCnt > 0, values, properties };
351 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
352 const r = parseSearchQuery(query);
354 const getFirstProp = (name: string) => r.properties[name] && r.properties[name][0];
355 const getPropValue = (name: string, value: string) => r.properties[name] && r.properties[name].find((v: string) => v === value);
356 const getProperties = () => {
357 if (r.properties.has) {
358 return r.properties.has.map((value: string) => {
359 const v = value.split(':');
370 searchValue: r.values.join(' '),
371 type: getResourceKind(getFirstProp('type')),
372 cluster: getClusterObjectType(getFirstProp('cluster')),
373 projectUuid: getFirstProp('project'),
374 inTrash: getPropValue('is', 'trashed') !== undefined,
375 dateFrom: getFirstProp('from'),
376 dateTo: getFirstProp('to'),
377 properties: getProperties(),
383 export const getFilters = (filterName: string, searchValue: string): string => {
384 const filter = new FilterBuilder();
386 const pq = parseSearchQuery(searchValue);
388 if (!pq.hasKeywords) {
390 .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
391 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
392 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
395 if (pq.properties.type) {
396 pq.values.forEach(v => {
398 switch (ResourceKind[pq.properties.type]) {
399 case ResourceKind.PROJECT:
400 prefix = GroupContentsResourcePrefix.PROJECT;
402 case ResourceKind.COLLECTION:
403 prefix = GroupContentsResourcePrefix.COLLECTION;
405 case ResourceKind.PROCESS:
406 prefix = GroupContentsResourcePrefix.PROCESS;
410 filter.addILike(filterName, v, prefix);
414 pq.values.forEach(v => {
416 .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
417 .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
418 .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
422 if (pq.properties.is && pq.properties.is === 'trashed') {
425 if (pq.properties.project) {
426 filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
429 if (pq.properties.from) {
430 filter.addGte('modified_at', buildDateFilter(pq.properties.from));
433 if (pq.properties.to) {
434 filter.addLte('modified_at', buildDateFilter(pq.properties.to));
437 // .addIsA("uuid", buildUuidFilter(resourceKind))
438 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
439 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
440 // .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
441 // .addLte('modified_at', buildDateFilter(dateTo))
442 // .addGte('modified_at', buildDateFilter(dateFrom))
443 // .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
447 .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
451 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
452 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
455 const buildDateFilter = (date?: string): string => {
456 return date ? date : '';
459 export const initAdvanceFormProjectsTree = () =>
460 (dispatch: Dispatch) => {
461 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
464 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
465 (dispatch: Dispatch) => {
466 dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
469 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
470 (dispatch: Dispatch) => {
471 dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
474 export const moveUp = () =>
475 (dispatch: Dispatch) => {
476 dispatch(searchBarActions.MOVE_UP());
479 export const moveDown = () =>
480 (dispatch: Dispatch) => {
481 dispatch(searchBarActions.MOVE_DOWN());