X-Git-Url: https://git.arvados.org/arvados-workbench2.git/blobdiff_plain/e952a4d2fac7c75375a9307f7f6676bd950bd0ed..519cf0aa43e6ac3085974506ff4eb1f0a70156c4:/src/store/search-bar/search-bar-actions.ts diff --git a/src/store/search-bar/search-bar-actions.ts b/src/store/search-bar/search-bar-actions.ts index f574b64c..54678b50 100644 --- a/src/store/search-bar/search-bar-actions.ts +++ b/src/store/search-bar/search-bar-actions.ts @@ -2,22 +2,28 @@ // // SPDX-License-Identifier: AGPL-3.0 -import { unionize, ofType, UnionOf } from "~/common/unionize"; +import { ofType, unionize, UnionOf } from "~/common/unionize"; import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service'; import { Dispatch } from 'redux'; -import { change, arrayPush } from 'redux-form'; +import { change, initialize, untouch } from 'redux-form'; import { RootState } from '~/store/store'; -import { initUserProject } from '~/store/tree-picker/tree-picker-actions'; +import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions'; import { ServiceRepository } from '~/services/services'; import { FilterBuilder } from "~/services/api/filter-builder"; -import { ResourceKind } from '~/models/resource'; -import { GroupClass } from '~/models/group'; +import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource'; import { SearchView } from '~/store/search-bar/search-bar-reducer'; -import { navigateToSearchResults, navigateTo } from '~/store/navigation/navigation-action'; +import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action'; import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions'; -import { initialize } from 'redux-form'; -import { SearchBarAdvanceFormData, PropertyValues } from '~/models/search-bar'; -import { debounce } from 'debounce'; +import { PropertyValue, SearchBarAdvancedFormData } from '~/models/search-bar'; +import * as _ from "lodash"; +import { getModifiedKeysValues } from "~/common/objects"; +import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions"; +import { Session } from "~/models/session"; +import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions"; +import { ListResults } from "~/services/common-service/common-service"; +import * as parser from './search-query/arv-parser'; +import { Keywords } from './search-query/arv-parser'; +import { Vocabulary, getTagKeyLabel, getTagValueLabel } from "~/models/vocabulary"; export const searchBarActions = unionize({ SET_CURRENT_VIEW: ofType(), @@ -25,15 +31,20 @@ export const searchBarActions = unionize({ CLOSE_SEARCH_VIEW: ofType<{}>(), SET_SEARCH_RESULTS: ofType(), SET_SEARCH_VALUE: ofType(), - SET_SAVED_QUERIES: ofType(), - UPDATE_SAVED_QUERY: ofType() + SET_SAVED_QUERIES: ofType(), + SET_RECENT_QUERIES: ofType(), + UPDATE_SAVED_QUERY: ofType(), + SET_SELECTED_ITEM: ofType(), + MOVE_UP: ofType<{}>(), + MOVE_DOWN: ofType<{}>(), + SELECT_FIRST_ITEM: ofType<{}>() }); export type SearchBarActions = UnionOf; -export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName'; +export const SEARCH_BAR_ADVANCED_FORM_NAME = 'searchBarAdvancedFormName'; -export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId'; +export const SEARCH_BAR_ADVANCED_FORM_PICKER_ID = 'searchBarAdvancedFormPickerId'; export const DEFAULT_SEARCH_DEBOUNCE = 1000; @@ -46,28 +57,71 @@ export const saveRecentQuery = (query: string) => export const loadRecentQueries = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - const recentSearchQueries = services.searchService.getRecentQueries(); - return recentSearchQueries || []; + const recentQueries = services.searchService.getRecentQueries(); + dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries)); + return recentQueries; }; -// Todo: create ids for particular searchQuery -export const saveQuery = (data: SearchBarAdvanceFormData) => +export const searchData = (searchValue: string) => + async (dispatch: Dispatch, getState: () => RootState) => { + const currentView = getState().searchBar.currentView; + dispatch(searchResultsPanelActions.CLEAR()); + dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue)); + if (searchValue.length > 0) { + dispatch(searchGroups(searchValue, 5)); + if (currentView === SearchView.BASIC) { + dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); + dispatch(navigateToSearchResults(searchValue)); + } + } + }; + +export const searchAdvancedData = (data: SearchBarAdvancedFormData) => + async (dispatch: Dispatch, getState: () => RootState) => { + dispatch(saveQuery(data)); + const searchValue = getState().searchBar.searchValue; + dispatch(searchResultsPanelActions.CLEAR()); + dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC)); + dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); + dispatch(navigateToSearchResults(searchValue)); + }; + +export const setSearchValueFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => + (dispatch: Dispatch, getState: () => RootState) => { + const searchValue = getState().searchBar.searchValue; + const value = getQueryFromAdvancedData({ + ...data, + searchValue + }, prevData); + dispatch(searchBarActions.SET_SEARCH_VALUE(value)); + }; + +export const setAdvancedDataFromSearchValue = (search: string, vocabulary: Vocabulary) => + async (dispatch: Dispatch) => { + const data = getAdvancedDataFromQuery(search, vocabulary); + dispatch(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data)); + if (data.projectUuid) { + await dispatch(activateSearchBarProject(data.projectUuid)); + dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID, id: data.projectUuid })); + } + }; + +const saveQuery = (data: SearchBarAdvancedFormData) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - const savedSearchQueries = services.searchService.getSavedQueries(); - const filteredQuery = savedSearchQueries.find(query => query.searchQuery === data.searchQuery); - if (data.saveQuery && data.searchQuery) { + const savedQueries = services.searchService.getSavedQueries(); + if (data.saveQuery && data.queryName) { + const filteredQuery = savedQueries.find(query => query.queryName === data.queryName); + data.searchValue = getState().searchBar.searchValue; if (filteredQuery) { services.searchService.editSavedQueries(data); - dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedSearchQueries)); - dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been sucessfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); + dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries)); + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); } else { services.searchService.saveQuery(data); - dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries)); - dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been sucessfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); + dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries)); + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); } } - dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC)); - dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); }; export const deleteSavedQuery = (id: number) => @@ -78,129 +132,274 @@ export const deleteSavedQuery = (id: number) => return savedSearchQueries || []; }; -export const editSavedQuery = (data: SearchBarAdvanceFormData) => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { +export const editSavedQuery = (data: SearchBarAdvancedFormData) => + (dispatch: Dispatch) => { dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED)); - dispatch(searchBarActions.SET_SEARCH_VALUE(data.searchQuery)); - dispatch(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data)); + dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data))); + dispatch(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data)); }; export const openSearchView = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(searchBarActions.OPEN_SEARCH_VIEW()); const savedSearchQueries = services.searchService.getSavedQueries(); dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries)); + dispatch(loadRecentQueries()); + dispatch(searchBarActions.OPEN_SEARCH_VIEW()); + dispatch(searchBarActions.SELECT_FIRST_ITEM()); }; export const closeSearchView = () => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - const isOpen = getState().searchBar.open; - if (isOpen) { - dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); - dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC)); - } + (dispatch: Dispatch) => { + dispatch(searchBarActions.SET_SELECTED_ITEM('')); + dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); + }; + +export const closeAdvanceView = () => + (dispatch: Dispatch) => { + dispatch(searchBarActions.SET_SEARCH_VALUE('')); + dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID })); + dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC)); }; export const navigateToItem = (uuid: string) => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + (dispatch: Dispatch) => { + dispatch(searchBarActions.SET_SELECTED_ITEM('')); dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); dispatch(navigateTo(uuid)); }; -export const searchData = (searchValue: string) => - async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - const currentView = getState().searchBar.currentView; - if (currentView !== SearchView.AUTOCOMPLETE) { - dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); - } +export const changeData = (searchValue: string) => + (dispatch: Dispatch, getState: () => RootState) => { dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue)); - dispatch(searchBarActions.SET_SEARCH_RESULTS([])); - if (searchValue) { - const filters = getFilters('name', searchValue); - const { items } = await services.groupsService.contents('', { - filters, - limit: 5, - recursive: true - }); - dispatch(searchBarActions.SET_SEARCH_RESULTS(items)); - } - if (currentView !== SearchView.AUTOCOMPLETE) { - dispatch(navigateToSearchResults); - } - - }; + const currentView = getState().searchBar.currentView; + const searchValuePresent = searchValue.length > 0; -export const changeData = (searchValue: string) => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue)); - if (searchValue.length > 0) { - dispatch(goToView(SearchView.AUTOCOMPLETE)); + if (currentView === SearchView.ADVANCED) { + dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE)); + } else if (searchValuePresent) { + dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE)); + dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue)); } else { - dispatch(goToView(SearchView.BASIC)); + dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC)); + dispatch(searchBarActions.SET_SEARCH_RESULTS([])); + dispatch(searchBarActions.SELECT_FIRST_ITEM()); } - debounceStartSearch(dispatch); }; -const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch(startSearch()), DEFAULT_SEARCH_DEBOUNCE); - -const startSearch = () => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { +export const submitData = (event: React.FormEvent) => + (dispatch: Dispatch, getState: () => RootState) => { + event.preventDefault(); const searchValue = getState().searchBar.searchValue; - if (searchValue.length > 0) { - dispatch(searchData(searchValue)); + dispatch(saveRecentQuery(searchValue)); + dispatch(loadRecentQueries()); + dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); + if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) { + dispatch(navigateTo(searchValue)); } else { dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue)); dispatch(searchBarActions.SET_SEARCH_RESULTS([])); + dispatch(searchResultsPanelActions.CLEAR()); + dispatch(navigateToSearchResults(searchValue)); } }; -export const submitData = (event: React.FormEvent) => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - event.preventDefault(); - const searchValue = getState().searchBar.searchValue; - dispatch(saveRecentQuery(searchValue)); - dispatch(searchDataOnEnter(searchValue)); - dispatch(loadRecentQueries()); - }; -export const searchDataOnEnter = (searchValue: string) => +const searchGroups = (searchValue: string, limit: number) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); - dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue)); - dispatch(searchBarActions.SET_SEARCH_RESULTS([])); - if (searchValue) { - const filters = getFilters('name', searchValue); - const { items } = await services.groupsService.contents('', { - filters, - limit: 5, - recursive: true - }); + const currentView = getState().searchBar.currentView; + + if (searchValue || currentView === SearchView.ADVANCED) { + const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue); + const sessions = getSearchSessions(clusterId, getState().auth.sessions); + const lists: ListResults[] = await Promise.all(sessions.map(session => { + const filters = queryToFilters(searchValue, session.apiRevision); + return services.groupsService.contents('', { + filters, + limit, + recursive: true + }, session); + })); + + const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]); dispatch(searchBarActions.SET_SEARCH_RESULTS(items)); } - dispatch(navigateToSearchResults); }; -export const getFilters = (filterName: string, searchValue: string): string => { - return new FilterBuilder() - .addIsA("uuid", [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS]) - .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION) - .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS) - .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT) - .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT) +const buildQueryFromKeyMap = (data: any, keyMap: string[][]) => { + let value = data.searchValue; + + const addRem = (field: string, key: string) => { + const v = data[key]; + // Remove previous search expression. + if (data.hasOwnProperty(key)) { + let pattern: string; + if (v === false) { + pattern = `${field.replace(':', '\\:\\s*')}\\s*`; + } else if (key.startsWith('prop-')) { + // On properties, only remove key:value duplicates, allowing + // multiple properties with the same key. + const oldValue = key.slice(5).split(':')[1]; + pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*${oldValue}\\s*`; + } else { + pattern = `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`; + } + value = value.replace(new RegExp(pattern), ''); + } + // Re-add it with the current search value. + if (v) { + const nv = v === true + ? `${field}` + : `${field}:${v}`; + // Always append to the end to keep user-entered text at the start. + value = value + ' ' + nv; + } + }; + keyMap.forEach(km => addRem(km[0], km[1])); + return value; +}; + +export const getQueryFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => { + let value = ''; + + const flatData = (data: SearchBarAdvancedFormData) => { + const fo = { + searchValue: data.searchValue, + type: data.type, + cluster: data.cluster, + projectUuid: data.projectUuid, + inTrash: data.inTrash, + dateFrom: data.dateFrom, + dateTo: data.dateTo, + }; + (data.properties || []).forEach(p => + fo[`prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] = `"${p.valueID || p.value}"` + ); + return fo; + }; + + const keyMap = [ + ['type', 'type'], + ['cluster', 'cluster'], + ['project', 'projectUuid'], + [`is:${parser.States.TRASHED}`, 'inTrash'], + ['from', 'dateFrom'], + ['to', 'dateTo'] + ]; + _.union(data.properties, prevData ? prevData.properties : []) + .forEach(p => keyMap.push( + [`has:"${p.keyID || p.key}"`, `prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] + )); + + const modified = getModifiedKeysValues(flatData(data), prevData ? flatData(prevData):{}); + value = buildQueryFromKeyMap( + {searchValue: data.searchValue, ...modified} as SearchBarAdvancedFormData, keyMap); + + value = value.trim(); + return value; +}; + +export const getAdvancedDataFromQuery = (query: string, vocabulary?: Vocabulary): SearchBarAdvancedFormData => { + const { tokens, searchString } = parser.parseSearchQuery(query); + const getValue = parser.getValue(tokens); + return { + searchValue: searchString, + type: getValue(Keywords.TYPE) as ResourceKind, + cluster: getValue(Keywords.CLUSTER), + projectUuid: getValue(Keywords.PROJECT), + inTrash: parser.isTrashed(tokens), + dateFrom: getValue(Keywords.FROM) || '', + dateTo: getValue(Keywords.TO) || '', + properties: vocabulary + ? parser.getProperties(tokens).map( + p => { + return { + keyID: p.key, + key: getTagKeyLabel(p.key, vocabulary), + valueID: p.value, + value: getTagValueLabel(p.key, p.value, vocabulary), + }; + }) + : parser.getProperties(tokens), + saveQuery: false, + queryName: '' + }; +}; + +export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => { + return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId)); +}; + +export const queryToFilters = (query: string, apiRevision: number) => { + const data = getAdvancedDataFromQuery(query); + const filter = new FilterBuilder(); + const resourceKind = data.type; + + if (data.searchValue) { + filter.addFullTextSearch(data.searchValue); + } + + if (data.projectUuid) { + filter.addEqual('owner_uuid', data.projectUuid); + } + + if (data.dateFrom) { + filter.addGte('modified_at', buildDateFilter(data.dateFrom)); + } + + if (data.dateTo) { + filter.addLte('modified_at', buildDateFilter(data.dateTo)); + } + + data.properties.forEach(p => { + if (p.value) { + if (apiRevision < 20200212) { + filter + .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT) + .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION); + } else { + filter + .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT) + .addContains(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION); + } + } + filter.addExists(p.key); + }); + + return filter + .addIsA("uuid", buildUuidFilter(resourceKind)) .getFilters(); }; -export const initAdvanceFormProjectsTree = () => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID)); +const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => { + return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS]; +}; + +const buildDateFilter = (date?: string): string => { + return date ? date : ''; +}; + +export const initAdvancedFormProjectsTree = () => + (dispatch: Dispatch) => { + dispatch(initUserProject(SEARCH_BAR_ADVANCED_FORM_PICKER_ID)); + }; + +export const changeAdvancedFormProperty = (propertyField: string, value: PropertyValue[] | string = '') => + (dispatch: Dispatch) => { + dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, value)); }; -export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value)); +export const resetAdvancedFormProperty = (propertyField: string) => + (dispatch: Dispatch) => { + dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, null)); + dispatch(untouch(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField)); }; -export const updateAdvanceFormProperties = (propertyValues: PropertyValues) => - (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues)); - }; \ No newline at end of file +export const moveUp = () => + (dispatch: Dispatch) => { + dispatch(searchBarActions.MOVE_UP()); + }; + +export const moveDown = () => + (dispatch: Dispatch) => { + dispatch(searchBarActions.MOVE_DOWN()); + };