Skip to content

Commit

Permalink
[Discover] Inline state modifying function to react (#89543) (#90612)
Browse files Browse the repository at this point in the history
  • Loading branch information
kertal authored Feb 8, 2021
1 parent bcddadb commit 77ef9fe
Show file tree
Hide file tree
Showing 16 changed files with 480 additions and 404 deletions.
111 changes: 1 addition & 110 deletions src/plugins/discover/public/application/angular/discover.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
syncQueryStateWithUrl,
} from '../../../../data/public';
import { getSortArray } from './doc_table';
import * as columnActions from './doc_table/actions/columns';
import indexTemplateLegacy from './discover_legacy.html';
import { addHelpMenuToAppChrome } from '../components/help_menu/help_menu_util';
import { discoverResponseHandler } from './response_handler';
Expand All @@ -43,13 +42,9 @@ import {
setBreadcrumbsTitle,
} from '../helpers/breadcrumbs';
import { validateTimeRange } from '../helpers/validate_time_range';
import { popularizeField } from '../helpers/popularize_field';
import { getSwitchIndexPatternAppState } from '../helpers/get_switch_index_pattern_app_state';
import { addFatalError } from '../../../../kibana_legacy/public';
import { METRIC_TYPE } from '@kbn/analytics';
import {
DEFAULT_COLUMNS_SETTING,
MODIFY_COLUMNS_ON_SWITCH,
SAMPLE_SIZE_SETTING,
SEARCH_FIELDS_FROM_SOURCE,
SEARCH_ON_PAGE_LOAD_SETTING,
Expand All @@ -69,12 +64,10 @@ const {
chrome,
data,
history: getHistory,
indexPatterns,
filterManager,
timefilter,
toastNotifications,
uiSettings: config,
trackUiMetric,
} = getServices();

const fetchStatuses = {
Expand Down Expand Up @@ -292,21 +285,6 @@ function discoverController($route, $scope, Promise) {
}
);

$scope.setIndexPattern = async (id) => {
const nextIndexPattern = await indexPatterns.get(id);
if (nextIndexPattern) {
const nextAppState = getSwitchIndexPatternAppState(
$scope.indexPattern,
nextIndexPattern,
$scope.state.columns,
$scope.state.sort,
config.get(MODIFY_COLUMNS_ON_SWITCH),
$scope.useNewFieldsApi
);
await setAppState(nextAppState);
}
};

// update data source when filters update
subscriptions.add(
subscribeWithScope(
Expand All @@ -327,6 +305,7 @@ function discoverController($route, $scope, Promise) {
sampleSize: config.get(SAMPLE_SIZE_SETTING),
timefield: getTimeField(),
savedSearch: savedSearch,
services,
indexPatternList: $route.current.locals.savedObjects.ip.list,
config: config,
setHeaderActionMenu: getHeaderActionMenuMounter(),
Expand All @@ -340,18 +319,8 @@ function discoverController($route, $scope, Promise) {
requests: new RequestAdapter(),
});

$scope.timefilterUpdateHandler = (ranges) => {
timefilter.setTime({
from: moment(ranges.from).toISOString(),
to: moment(ranges.to).toISOString(),
mode: 'absolute',
});
};
$scope.minimumVisibleRows = 50;
$scope.fetchStatus = fetchStatuses.UNINITIALIZED;
$scope.showSaveQuery = capabilities.discover.saveQuery;
$scope.showTimeCol =
!config.get('doc_table:hideTimeColumn', false) && $scope.indexPattern.timeFieldName;

let abortController;
$scope.$on('$destroy', () => {
Expand Down Expand Up @@ -495,12 +464,6 @@ function discoverController($route, $scope, Promise) {
)
);

$scope.changeInterval = (interval) => {
if (interval) {
setAppState({ interval });
}
};

$scope.$watchMulti(
['rows', 'fetchStatus'],
(function updateResultState() {
Expand Down Expand Up @@ -606,19 +569,6 @@ function discoverController($route, $scope, Promise) {
}
};

$scope.updateSavedQueryId = (newSavedQueryId) => {
if (newSavedQueryId) {
setAppState({ savedQuery: newSavedQueryId });
} else {
// remove savedQueryId from state
const state = {
...appStateContainer.getState(),
};
delete state.savedQuery;
appStateContainer.set(state);
}
};

function getDimensions(aggs, timeRange) {
const [metric, agg] = aggs;
agg.params.timeRange = timeRange;
Expand Down Expand Up @@ -752,65 +702,6 @@ function discoverController($route, $scope, Promise) {
return Promise.resolve();
};

$scope.setSortOrder = function setSortOrder(sort) {
setAppState({ sort });
};

// TODO: On array fields, negating does not negate the combination, rather all terms
$scope.filterQuery = function (field, values, operation) {
const { indexPattern } = $scope;

popularizeField(indexPattern, field.name, indexPatterns);
const newFilters = esFilters.generateFilters(
filterManager,
field,
values,
operation,
$scope.indexPattern.id
);
if (trackUiMetric) {
trackUiMetric(METRIC_TYPE.CLICK, 'filter_added');
}
return filterManager.addFilters(newFilters);
};

$scope.addColumn = function addColumn(columnName) {
const { indexPattern, useNewFieldsApi } = $scope;
if (capabilities.discover.save) {
popularizeField(indexPattern, columnName, indexPatterns);
}
const columns = columnActions.addColumn($scope.state.columns, columnName, useNewFieldsApi);
setAppState({ columns });
};

$scope.removeColumn = function removeColumn(columnName) {
const { indexPattern, useNewFieldsApi } = $scope;
if (capabilities.discover.save) {
popularizeField(indexPattern, columnName, indexPatterns);
}
const columns = columnActions.removeColumn($scope.state.columns, columnName, useNewFieldsApi);
// The state's sort property is an array of [sortByColumn,sortDirection]
const sort = $scope.state.sort.length
? $scope.state.sort.filter((subArr) => subArr[0] !== columnName)
: [];
setAppState({ columns, sort });
};

$scope.moveColumn = function moveColumn(columnName, newIndex) {
const columns = columnActions.moveColumn($scope.state.columns, columnName, newIndex);
setAppState({ columns });
};

$scope.setColumns = function setColumns(columns) {
// remove first element of columns if it's the configured timeFieldName, which is prepended automatically
const actualColumns =
$scope.indexPattern.timeFieldName && $scope.indexPattern.timeFieldName === columns[0]
? columns.slice(1)
: columns;
$scope.state = { ...$scope.state, columns: actualColumns };
setAppState({ columns: actualColumns });
};

async function setupVisualization() {
// If no timefield has been specified we don't create a histogram of messages
if (!getTimeField()) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,16 @@
hits="hits"
index-pattern="indexPattern"
minimum-visible-rows="minimumVisibleRows"
on-add-column="addColumn"
on-add-filter="filterQuery"
on-move-column="moveColumn"
on-change-interval="changeInterval"
on-remove-column="removeColumn"
on-set-columns="setColumns"
on-skip-bottom-button-click="onSkipBottomButtonClick"
on-sort="setSortOrder"
opts="opts"
reset-query="resetQuery"
result-state="resultState"
rows="rows"
search-source="searchSource"
set-index-pattern="setIndexPattern"
show-save-query="showSaveQuery"
state="state"
time-filter-update-handler="timefilterUpdateHandler"
time-range="timeRange"
top-nav-menu="topNavMenu"
update-query="handleRefresh"
update-saved-query-id="updateSavedQueryId"
use-new-fields-api="useNewFieldsApi"
unmapped-fields-config="unmappedFieldsConfig"
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { Capabilities } from 'kibana/public';
import { popularizeField } from '../../../helpers/popularize_field';
import { IndexPattern, IndexPatternsContract } from '../../../../kibana_services';
import { AppState } from '../../discover_state';

/**
* Helper function to provide a fallback to a single _source column if the given array of columns
Expand Down Expand Up @@ -47,3 +51,60 @@ export function moveColumn(columns: string[], columnName: string, newIndex: numb
modifiedColumns.splice(newIndex, 0, columnName); // insert before new index
return modifiedColumns;
}

export function getStateColumnActions({
capabilities,
indexPattern,
indexPatterns,
useNewFieldsApi,
setAppState,
state,
}: {
capabilities: Capabilities;
indexPattern: IndexPattern;
indexPatterns: IndexPatternsContract;
useNewFieldsApi: boolean;
setAppState: (state: Partial<AppState>) => void;
state: AppState;
}) {
function onAddColumn(columnName: string) {
if (capabilities.discover.save) {
popularizeField(indexPattern, columnName, indexPatterns);
}
const columns = addColumn(state.columns || [], columnName, useNewFieldsApi);
setAppState({ columns });
}

function onRemoveColumn(columnName: string) {
if (capabilities.discover.save) {
popularizeField(indexPattern, columnName, indexPatterns);
}
const columns = removeColumn(state.columns || [], columnName, useNewFieldsApi);
// The state's sort property is an array of [sortByColumn,sortDirection]
const sort =
state.sort && state.sort.length
? state.sort.filter((subArr) => subArr[0] !== columnName)
: [];
setAppState({ columns, sort });
}

function onMoveColumn(columnName: string, newIndex: number) {
const columns = moveColumn(state.columns || [], columnName, newIndex);
setAppState({ columns });
}

function onSetColumns(columns: string[]) {
// remove first element of columns if it's the configured timeFieldName, which is prepended automatically
const actualColumns =
indexPattern.timeFieldName && indexPattern.timeFieldName === columns[0]
? columns.slice(1)
: columns;
setAppState({ columns: actualColumns });
}
return {
onAddColumn,
onRemoveColumn,
onMoveColumn,
onSetColumns,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { Discover } from './discover';

export function createDiscoverDirective(reactDirective: any) {
Expand All @@ -18,24 +17,15 @@ export function createDiscoverDirective(reactDirective: any) {
['hits', { watchDepth: 'reference' }],
['indexPattern', { watchDepth: 'reference' }],
['minimumVisibleRows', { watchDepth: 'reference' }],
['onAddColumn', { watchDepth: 'reference' }],
['onAddFilter', { watchDepth: 'reference' }],
['onChangeInterval', { watchDepth: 'reference' }],
['onMoveColumn', { watchDepth: 'reference' }],
['onRemoveColumn', { watchDepth: 'reference' }],
['onSetColumns', { watchDepth: 'reference' }],
['onSkipBottomButtonClick', { watchDepth: 'reference' }],
['onSort', { watchDepth: 'reference' }],
['opts', { watchDepth: 'reference' }],
['resetQuery', { watchDepth: 'reference' }],
['resultState', { watchDepth: 'reference' }],
['rows', { watchDepth: 'reference' }],
['savedSearch', { watchDepth: 'reference' }],
['searchSource', { watchDepth: 'reference' }],
['setIndexPattern', { watchDepth: 'reference' }],
['showSaveQuery', { watchDepth: 'reference' }],
['state', { watchDepth: 'reference' }],
['timefilterUpdateHandler', { watchDepth: 'reference' }],
['timeRange', { watchDepth: 'reference' }],
['topNavMenu', { watchDepth: 'reference' }],
['updateQuery', { watchDepth: 'reference' }],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { shallowWithIntl } from '@kbn/test/jest';
import { Discover } from './discover';
import { esHits } from '../../__mocks__/es_hits';
import { indexPatternMock } from '../../__mocks__/index_pattern';
import { DiscoverServices } from '../../build_services';
import { GetStateReturn } from '../angular/discover_state';
import { savedSearchMock } from '../../__mocks__/saved_search';
import { createSearchSourceMock } from '../../../../data/common/search/search_source/mocks';
Expand Down Expand Up @@ -46,7 +47,14 @@ jest.mock('../../kibana_services', () => {

function getProps(indexPattern: IndexPattern): DiscoverProps {
const searchSourceMock = createSearchSourceMock({});
const state = ({} as unknown) as GetStateReturn;
const services = ({
capabilities: {
discover: {
save: true,
},
},
uiSettings: mockUiSettings,
} as unknown) as DiscoverServices;

return {
fetch: jest.fn(),
Expand All @@ -56,14 +64,7 @@ function getProps(indexPattern: IndexPattern): DiscoverProps {
hits: esHits.length,
indexPattern,
minimumVisibleRows: 10,
onAddColumn: jest.fn(),
onAddFilter: jest.fn(),
onChangeInterval: jest.fn(),
onMoveColumn: jest.fn(),
onRemoveColumn: jest.fn(),
onSetColumns: jest.fn(),
onSkipBottomButtonClick: jest.fn(),
onSort: jest.fn(),
opts: {
config: mockUiSettings,
data: dataPluginMock.createStartContract(),
Expand All @@ -74,20 +75,18 @@ function getProps(indexPattern: IndexPattern): DiscoverProps {
navigateTo: jest.fn(),
sampleSize: 10,
savedSearch: savedSearchMock,
setAppState: jest.fn(),
setHeaderActionMenu: jest.fn(),
stateContainer: state,
timefield: indexPattern.timeFieldName || '',
setAppState: jest.fn(),
services,
stateContainer: {} as GetStateReturn,
},
resetQuery: jest.fn(),
resultState: 'ready',
rows: esHits,
searchSource: searchSourceMock,
setIndexPattern: jest.fn(),
state: { columns: [] },
timefilterUpdateHandler: jest.fn(),
updateQuery: jest.fn(),
updateSavedQueryId: jest.fn(),
};
}

Expand Down
Loading

0 comments on commit 77ef9fe

Please sign in to comment.