15781: Fixes property removal on the advanced search editor.
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
index 68efb4e6f2f6b0651a8aa409f65fd5f2b4d72a61..54678b504b52c0f22ffd83c77071033b74e70821 100644 (file)
@@ -5,17 +5,16 @@
 import { ofType, unionize, UnionOf } from "~/common/unionize";
 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
 import { Dispatch } from 'redux';
-import { arrayPush, change, initialize } from 'redux-form';
+import { change, initialize, untouch } from 'redux-form';
 import { RootState } from '~/store/store';
 import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions';
 import { ServiceRepository } from '~/services/services';
 import { FilterBuilder } from "~/services/api/filter-builder";
-import { ResourceKind, isResourceUuid, extractUuidKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource';
+import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource';
 import { SearchView } from '~/store/search-bar/search-bar-reducer';
 import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
-import { PropertyValue, SearchBarAdvanceFormData } 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";
@@ -24,6 +23,7 @@ import { searchResultsPanelActions } from "~/store/search-results-panel/search-r
 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<string>(),
@@ -31,9 +31,9 @@ export const searchBarActions = unionize({
     CLOSE_SEARCH_VIEW: ofType<{}>(),
     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
     SET_SEARCH_VALUE: ofType<string>(),
-    SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
+    SET_SAVED_QUERIES: ofType<SearchBarAdvancedFormData[]>(),
     SET_RECENT_QUERIES: ofType<string[]>(),
-    UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
+    UPDATE_SAVED_QUERY: ofType<SearchBarAdvancedFormData[]>(),
     SET_SELECTED_ITEM: ofType<string>(),
     MOVE_UP: ofType<{}>(),
     MOVE_DOWN: ofType<{}>(),
@@ -42,9 +42,9 @@ export const searchBarActions = unionize({
 
 export type SearchBarActions = UnionOf<typeof searchBarActions>;
 
-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;
 
@@ -71,21 +71,22 @@ export const searchData = (searchValue: string) =>
             dispatch<any>(searchGroups(searchValue, 5));
             if (currentView === SearchView.BASIC) {
                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
-                dispatch(navigateToSearchResults);
+                dispatch(navigateToSearchResults(searchValue));
             }
         }
     };
 
-export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
-    async (dispatch: Dispatch) => {
+export const searchAdvancedData = (data: SearchBarAdvancedFormData) =>
+    async (dispatch: Dispatch, getState: () => RootState) => {
         dispatch<any>(saveQuery(data));
+        const searchValue = getState().searchBar.searchValue;
         dispatch(searchResultsPanelActions.CLEAR());
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
-        dispatch(navigateToSearchResults);
+        dispatch(navigateToSearchResults(searchValue));
     };
 
-export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
+export const setSearchValueFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) =>
     (dispatch: Dispatch, getState: () => RootState) => {
         const searchValue = getState().searchBar.searchValue;
         const value = getQueryFromAdvancedData({
@@ -95,17 +96,17 @@ export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, p
         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
     };
 
-export const setAdvancedDataFromSearchValue = (search: string) =>
+export const setAdvancedDataFromSearchValue = (search: string, vocabulary: Vocabulary) =>
     async (dispatch: Dispatch) => {
-        const data = getAdvancedDataFromQuery(search);
-        dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
+        const data = getAdvancedDataFromQuery(search, vocabulary);
+        dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
         if (data.projectUuid) {
             await dispatch<any>(activateSearchBarProject(data.projectUuid));
-            dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
+            dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID, id: data.projectUuid }));
         }
     };
 
-const saveQuery = (data: SearchBarAdvanceFormData) =>
+const saveQuery = (data: SearchBarAdvancedFormData) =>
     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
         const savedQueries = services.searchService.getSavedQueries();
         if (data.saveQuery && data.queryName) {
@@ -131,11 +132,11 @@ export const deleteSavedQuery = (id: number) =>
         return savedSearchQueries || [];
     };
 
-export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
+export const editSavedQuery = (data: SearchBarAdvancedFormData) =>
     (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
         dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
-        dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
+        dispatch<any>(initialize(SEARCH_BAR_ADVANCED_FORM_NAME, data));
     };
 
 export const openSearchView = () =>
@@ -156,7 +157,7 @@ export const closeSearchView = () =>
 export const closeAdvanceView = () =>
     (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
-        dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
+        dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCED_FORM_PICKER_ID }));
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
     };
 
@@ -198,17 +199,11 @@ export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
             dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
             dispatch(searchResultsPanelActions.CLEAR());
-            dispatch(navigateToSearchResults);
+            dispatch(navigateToSearchResults(searchValue));
         }
     };
 
 
-const startSearch = () =>
-    (dispatch: Dispatch, getState: () => RootState) => {
-        const searchValue = getState().searchBar.searchValue;
-        dispatch<any>(searchData(searchValue));
-    };
-
 const searchGroups = (searchValue: string, limit: number) =>
     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         const currentView = getState().searchBar.currentView;
@@ -217,7 +212,7 @@ const searchGroups = (searchValue: string, limit: number) =>
             const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
             const sessions = getSearchSessions(clusterId, getState().auth.sessions);
             const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
-                const filters = queryToFilters(searchValue);
+                const filters = queryToFilters(searchValue, session.apiRevision);
                 return services.groupsService.contents('', {
                     filters,
                     limit,
@@ -230,41 +225,43 @@ const searchGroups = (searchValue: string, limit: number) =>
         }
     };
 
-const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
+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)) {
-            const pattern = v === false
-                ? `${field.replace(':', '\\:\\s*')}\\s*`
-                : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
+            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}`;
-
-            if (mode === 'rebuild') {
-                value = value + ' ' + nv;
-            } else {
-                value = nv + ' ' + value;
-            }
+            // 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: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
+export const getQueryFromAdvancedData = (data: SearchBarAdvancedFormData, prevData?: SearchBarAdvancedFormData) => {
     let value = '';
 
-    const flatData = (data: SearchBarAdvanceFormData) => {
+    const flatData = (data: SearchBarAdvancedFormData) => {
         const fo = {
             searchValue: data.searchValue,
             type: data.type,
@@ -274,7 +271,9 @@ export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevDat
             dateFrom: data.dateFrom,
             dateTo: data.dateTo,
         };
-        (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
+        (data.properties || []).forEach(p =>
+            fo[`prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`] = `"${p.valueID || p.value}"`
+            );
         return fo;
     };
 
@@ -287,25 +286,19 @@ export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevDat
         ['to', 'dateTo']
     ];
     _.union(data.properties, prevData ? prevData.properties : [])
-        .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
+        .forEach(p => keyMap.push(
+            [`has:"${p.keyID || p.key}"`, `prop-"${p.keyID || p.key}":"${p.valueID || p.value}"`]
+        ));
 
-    if (prevData) {
-        const fd = flatData(data);
-        const pfd = flatData(prevData);
-        const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
-        value = buildQueryFromKeyMap({
-            searchValue: data.searchValue,
-            ...obj
-        } as SearchBarAdvanceFormData, keyMap, "reuse");
-    } else {
-        value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
-    }
+    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): SearchBarAdvanceFormData => {
+export const getAdvancedDataFromQuery = (query: string, vocabulary?: Vocabulary): SearchBarAdvancedFormData => {
     const { tokens, searchString } = parser.parseSearchQuery(query);
     const getValue = parser.getValue(tokens);
     return {
@@ -316,7 +309,17 @@ export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormDat
         inTrash: parser.isTrashed(tokens),
         dateFrom: getValue(Keywords.FROM) || '',
         dateTo: getValue(Keywords.TO) || '',
-        properties: parser.getProperties(tokens),
+        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: ''
     };
@@ -326,7 +329,7 @@ export const getSearchSessions = (clusterId: string | undefined, sessions: Sessi
     return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
 };
 
-export const queryToFilters = (query: string) => {
+export const queryToFilters = (query: string, apiRevision: number) => {
     const data = getAdvancedDataFromQuery(query);
     const filter = new FilterBuilder();
     const resourceKind = data.type;
@@ -336,7 +339,7 @@ export const queryToFilters = (query: string) => {
     }
 
     if (data.projectUuid) {
-        filter.addEqual('ownerUuid', data.projectUuid);
+        filter.addEqual('owner_uuid', data.projectUuid);
     }
 
     if (data.dateFrom) {
@@ -349,9 +352,15 @@ export const queryToFilters = (query: string) => {
 
     data.properties.forEach(p => {
         if (p.value) {
-            filter
-                .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
-                .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
+            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);
     });
@@ -369,19 +378,20 @@ const buildDateFilter = (date?: string): string => {
     return date ? date : '';
 };
 
-export const initAdvanceFormProjectsTree = () =>
+export const initAdvancedFormProjectsTree = () =>
     (dispatch: Dispatch) => {
-        dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
+        dispatch<any>(initUserProject(SEARCH_BAR_ADVANCED_FORM_PICKER_ID));
     };
 
-export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
+export const changeAdvancedFormProperty = (propertyField: string, value: PropertyValue[] | string = '') =>
     (dispatch: Dispatch) => {
-        dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
+        dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, value));
     };
 
-export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
+export const resetAdvancedFormProperty = (propertyField: string) =>
     (dispatch: Dispatch) => {
-        dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
+        dispatch(change(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField, null));
+        dispatch(untouch(SEARCH_BAR_ADVANCED_FORM_NAME, propertyField));
     };
 
 export const moveUp = () =>