Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/platform/plugins/shared/discover/common/app_locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import type { VIEW_MODE, NEW_TAB_ID } from './constants';

export const DISCOVER_APP_LOCATOR = 'DISCOVER_APP_LOCATOR';

export type DiscoverProfileUrlState = Record<string, SerializableRecord>;

export interface DiscoverAppLocatorParams extends SerializableRecord {
/**
* Optionally set saved search ID.
Expand Down Expand Up @@ -75,6 +77,11 @@ export interface DiscoverAppLocatorParams extends SerializableRecord {
*/
tab?: { id: typeof NEW_TAB_ID | string; label?: string };

/**
* Optionally set URL-synced profile state.
*/
profileUrlState?: DiscoverProfileUrlState;

/**
* Columns displayed in the table
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@ import type { GlobalQueryStateFromUrl } from '@kbn/data-plugin/public';
import { isFilterPinned, isOfAggregateQueryType } from '@kbn/es-query';
import type { setStateToKbnUrl as setStateToKbnUrlCommon } from '@kbn/kibana-utils-plugin/common';
import type {
DiscoverProfileUrlState,
DiscoverAppLocatorGetLocation,
DiscoverAppLocatorParams,
MainHistoryLocationState,
} from './app_locator';
import type { DiscoverAppState } from '../public';
import { createDataViewDataSource, createEsqlDataSource } from './data_sources';
import { APP_STATE_URL_KEY, GLOBAL_STATE_URL_KEY, TAB_STATE_URL_KEY } from './constants';
import {
APP_STATE_URL_KEY,
GLOBAL_STATE_URL_KEY,
PROFILE_STATE_URL_KEY,
TAB_STATE_URL_KEY,
} from './constants';

export const appLocatorGetLocationCommon = async (
{
Expand All @@ -38,7 +44,7 @@ export const appLocatorGetLocationCommon = async (
path = `${path}?searchSessionId=${searchSessionId}`;
}

const { appState, globalState, state } = parseAppLocatorParams(params);
const { appState, globalState, profileUrlState, state } = parseAppLocatorParams(params);

if (Object.keys(globalState).length) {
path = setStateToKbnUrl<GlobalQueryStateFromUrl>(
Expand All @@ -53,6 +59,10 @@ export const appLocatorGetLocationCommon = async (
path = setStateToKbnUrl(APP_STATE_URL_KEY, appState, { useHash }, path);
}

if (profileUrlState && Object.keys(profileUrlState).length) {
path = setStateToKbnUrl(PROFILE_STATE_URL_KEY, profileUrlState, { useHash }, path);
}

if (tab?.id) {
path = setStateToKbnUrl(
TAB_STATE_URL_KEY,
Expand Down Expand Up @@ -91,10 +101,13 @@ export const parseAppLocatorParams = (params: DiscoverAppLocatorParams) => {
sampleSize,
isAlertResults,
esqlControls,
profileUrlState,
} = params;

const appState: Partial<DiscoverAppState> = {};
const globalState: GlobalQueryStateFromUrl = {};
const parsedProfileUrlState: DiscoverProfileUrlState | undefined =
profileUrlState && Object.keys(profileUrlState).length > 0 ? profileUrlState : undefined;

if (query) appState.query = query;
if (filters && filters.length) appState.filters = filters?.filter((f) => !isFilterPinned(f));
Expand Down Expand Up @@ -123,5 +136,5 @@ export const parseAppLocatorParams = (params: DiscoverAppLocatorParams) => {
if (isAlertResults) state.isAlertResults = isAlertResults;
if (esqlControls) state.esqlControls = esqlControls;

return { appState, globalState, state };
return { appState, globalState, profileUrlState: parsedProfileUrlState, state };
};
1 change: 1 addition & 0 deletions src/platform/plugins/shared/discover/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const NEW_TAB_ID = 'new' as const;
*/
export const APP_STATE_URL_KEY = '_a';
export const GLOBAL_STATE_URL_KEY = '_g';
export const PROFILE_STATE_URL_KEY = '_p';
export const TAB_STATE_URL_KEY = '_tab'; // `_t` is already used by Kibana for time, so we use `_tab` here

/**
Expand Down
7 changes: 6 additions & 1 deletion src/platform/plugins/shared/discover/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@
export const PLUGIN_ID = 'discover';
export const APP_ICON = 'discoverApp';

export { APP_STATE_URL_KEY, EMBEDDABLE_TRANSFORMS_FEATURE_FLAG_KEY } from './constants';
export {
APP_STATE_URL_KEY,
EMBEDDABLE_TRANSFORMS_FEATURE_FLAG_KEY,
PROFILE_STATE_URL_KEY,
} from './constants';
export { DISCOVER_APP_LOCATOR } from './app_locator';
export type {
DiscoverAppLocator,
DiscoverAppLocatorParams,
DiscoverProfileUrlState,
MainHistoryLocationState,
} from './app_locator';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ function createInternalStateStoreMock({
const tabsStorageManager = createTabsStorageManager({
urlStateStorage: stateStorageContainer,
storage: services.storage,
profileStateRegistry: services.profileStateRegistry,
});
const searchSessionManager = new DiscoverSearchSessionManager({
history: services.history,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import type { SearchSourceDependencies } from '@kbn/data-plugin/common';
import type { SearchResponse } from '@elastic/elasticsearch/lib/api/types';
import { createElement } from 'react';
import { createContextAwarenessMocks } from '../context_awareness/__mocks__';
import { ProfileStateRegistry } from '../context_awareness';
import { DiscoverEBTManager } from '../ebt_manager';
import { discoverSharedPluginMock } from '@kbn/discover-shared-plugin/public/mocks';
import { createUrlTrackerMock } from './url_tracker.mock';
Expand Down Expand Up @@ -307,6 +308,7 @@ export function createDiscoverServicesMock(): DiscoverServices {
singleDocLocator: { getRedirectUrl: jest.fn(() => '') },
urlTracker: createUrlTrackerMock(),
profilesManager: profilesManagerMock,
profileStateRegistry: new ProfileStateRegistry(),
ebtManager: new DiscoverEBTManager(),
cps: cpsPluginMock.createStartContract(),
setHeaderActionMenu: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { LoadingIndicator } from '../../components/common/loading_indicator';
import { useDataView } from '../../hooks/use_data_view';
import type { ContextHistoryLocationState } from './services/locator';
import { useDiscoverServices } from '../../hooks/use_discover_services';
import { useRootProfile } from '../../context_awareness';
import { EMPTY_CONTEXT_AWARENESS_TOOLKIT, useRootProfile } from '../../context_awareness';
import { ScopedServicesProvider } from '../../components/scoped_services_provider';

export interface ContextUrlParams {
Expand Down Expand Up @@ -104,7 +104,9 @@ export function ContextAppRoute() {
profilesManager.createScopedProfilesManager({
scopedEbtManager,
toolkit: {
...EMPTY_CONTEXT_AWARENESS_TOOLKIT,
actions: {
...EMPTY_CONTEXT_AWARENESS_TOOLKIT.actions,
addFilter,
setExpandedDoc,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ interface BuildShareOptionsParams {
discoverParams: AppMenuDiscoverParams;
services: DiscoverServices;
currentTab: TabState;
profileUrlState?: DiscoverAppLocatorParams['profileUrlState'];
persistedDiscoverSession: DiscoverSession | undefined;
totalHitsState: DataTotalHitsMsg;
hasUnsavedChanges: boolean;
Expand All @@ -50,6 +51,7 @@ export const buildShareOptions = async ({
discoverParams,
services,
currentTab,
profileUrlState,
persistedDiscoverSession,
totalHitsState,
hasUnsavedChanges,
Expand Down Expand Up @@ -84,6 +86,7 @@ export const buildShareOptions = async ({
...(dataView?.isPersisted()
? { dataViewId: dataView?.id }
: { dataViewSpec: dataView?.toMinimalSpec() }),
...(profileUrlState ? { profileUrlState } : {}),
filters,
timeRange,
refreshInterval,
Expand Down Expand Up @@ -256,6 +259,7 @@ export const getShareAppMenuItem = ({
hasIntegrations,
hasUnsavedChanges,
currentTab,
profileUrlState,
persistedDiscoverSession,
totalHitsState,
intl,
Expand All @@ -265,6 +269,7 @@ export const getShareAppMenuItem = ({
hasIntegrations: boolean;
hasUnsavedChanges: boolean;
currentTab: TabState;
profileUrlState?: DiscoverAppLocatorParams['profileUrlState'];
persistedDiscoverSession: DiscoverSession | undefined;
totalHitsState: DataTotalHitsMsg;
intl: IntlShape;
Expand All @@ -278,6 +283,7 @@ export const getShareAppMenuItem = ({
discoverParams,
services,
currentTab,
profileUrlState,
persistedDiscoverSession,
totalHitsState,
hasUnsavedChanges,
Expand Down Expand Up @@ -306,6 +312,7 @@ export const getShareAppMenuItem = ({
discoverParams,
services,
currentTab,
profileUrlState,
persistedDiscoverSession,
totalHitsState,
hasUnsavedChanges,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
import { useProfileAccessor } from '../../../../context_awareness';
import {
internalStateActions,
selectTabRuntimeState,
selectTabSavedSearchByValueAttributes,
useCurrentDataView,
useCurrentTabSelector,
Expand All @@ -52,6 +53,7 @@ import {
useRuntimeStateManager,
} from '../../state_management/redux';
import type { DiscoverAppState } from '../../state_management/redux';
import { getProfileUrlState } from '../../state_management/utils/get_profile_url_state';
import { useCurrentTabMenuActions } from '../../hooks/use_current_tab_menu_actions';
import { useDataState } from '../../hooks/use_data_state';
import { TransferAction } from '../../../../plugin_imports/embeddable_editor_service';
Expand Down Expand Up @@ -146,6 +148,16 @@ export const useTopNavLinks = ({

const canCreateESQLRule = !!services.capabilities.alertingVTwo;
const showCreateRuleV2 = isEsqlMode && canCreateESQLRule;
const activeProfileStateDefinition = selectTabRuntimeState(runtimeStateManager, currentTab.id)
.scopedProfilesManager$.getValue()
.getContexts().dataSourceContext.profileState;
const profileUrlState = activeProfileStateDefinition
? getProfileUrlState({
definition: activeProfileStateDefinition,
profileState: currentTab.profileState,
profileStateRegistry: services.profileStateRegistry,
})
: undefined;

const appMenuItems: DiscoverAppMenuItemType[] = useMemo(() => {
const items: DiscoverAppMenuItemType[] = [];
Expand Down Expand Up @@ -227,6 +239,7 @@ export const useTopNavLinks = ({
hasIntegrations: hasShareIntegration,
hasUnsavedChanges,
currentTab,
profileUrlState,
persistedDiscoverSession,
totalHitsState,
intl,
Expand Down Expand Up @@ -288,6 +301,7 @@ export const useTopNavLinks = ({
currentDataView,
currentTab,
isDataViewMode,
profileUrlState,
openInspector,
persistedDiscoverSession,
hasShareIntegration,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { fetchAll, type CommonFetchParams, fetchMoreDocuments } from '../data_fe
import { sendResetMsg } from '../hooks/use_saved_search_messages';
import { getFetch$ } from '../data_fetching/get_fetch_observable';
import { getDefaultProfileState, getProfileStateSnapshot } from './utils/default_profile_state';
import { getRestoredProfileUrlState } from './utils/get_profile_url_state';
import type { InternalStateStore, RuntimeStateManager, TabActionInjector, TabState } from './redux';
import { internalStateActions, selectTabRuntimeState } from './redux';
import { buildEsqlFetchSubscribe } from './utils/build_esql_fetch_subscribe';
Expand Down Expand Up @@ -383,7 +384,39 @@ export function getDataStateContainer({

// If the data source profile changed, we may need to restore previous profile state
if (didProfileChange) {
const profileId = scopedProfilesManager.getContexts().dataSourceContext.profileId;
const { dataSourceContext } = scopedProfilesManager.getContexts();
const profileId = dataSourceContext.profileId;
const activeProfileStateDefinition = dataSourceContext.profileState;
const initialProfileUrlState = getCurrentTab().initialProfileUrlState;

if (isFirstResolution && initialProfileUrlState) {
if (activeProfileStateDefinition) {
const restoredProfileUrlState = getRestoredProfileUrlState({
definition: activeProfileStateDefinition,
profileStateRegistry: services.profileStateRegistry,
profileUrlState: initialProfileUrlState,
});

if (restoredProfileUrlState) {
internalState.dispatch(
injectCurrentTab(internalStateActions.setProfileState)({
key: activeProfileStateDefinition.key,
profileState: {
...(getCurrentTab().profileState[activeProfileStateDefinition.key] ?? {}),
...restoredProfileUrlState,
},
})
);
}
}

internalState.dispatch(
injectCurrentTab(internalStateActions.setInitialProfileUrlState)({
initialProfileUrlState: undefined,
})
);
}

const profileStateSnapshot =
getCurrentTab().defaultProfileState.snapshotsByProfileId[profileId];
const profileStateUpdate = getProfileStateSnapshot(
Expand Down Expand Up @@ -428,6 +461,10 @@ export function getDataStateContainer({
injectCurrentTab(internalStateActions.syncProfileStateSnapshot)({})
);
}

await internalState.dispatch(
injectCurrentTab(internalStateActions.updateProfileUrlStateAndReplaceUrl)()
);
}

const dataView = currentDataView$.getValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const useStateManagers = ({
createTabsStorageManager({
urlStateStorage,
storage: services.storage,
profileStateRegistry: services.profileStateRegistry,
enabled: tabsEnabled,
})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ import { loadAndResolveDataView } from '../../utils/resolve_data_view';
import { isDataViewSource } from '../../../../../../common/data_sources';
import { isRefreshIntervalValid, isTimeRangeValid } from '../../../../../utils/validate_time';
import { getValidFilters } from '../../../../../utils/get_valid_filters';
import { APP_STATE_URL_KEY } from '../../../../../../common';
import { APP_STATE_URL_KEY, type DiscoverProfileUrlState } from '../../../../../../common';
import { selectTabRuntimeState } from '../runtime_state';
import type { ConnectedCustomizationService } from '../../../../../customizations';
import { selectTab } from '../selectors';
import type { TabState, TabStateGlobalState } from '../types';
import { GLOBAL_STATE_URL_KEY } from '../../../../../../common/constants';
import { GLOBAL_STATE_URL_KEY, PROFILE_STATE_URL_KEY } from '../../../../../../common/constants';
import { fromSavedObjectTabToSearchSource } from '../tab_mapping_utils';
import { createInternalStateAsyncThunk, extractEsqlVariables } from '../utils';
import { fetchData, updateAttributes } from './tab_state';
Expand Down Expand Up @@ -111,12 +111,21 @@ export const initializeSingleTab = createInternalStateAsyncThunk(
// to avoid race conditions if the URL changes during tab initialization,
// e.g. if the user quickly switches tabs
const urlGlobalState = urlStateStorage.get<GlobalQueryStateFromUrl>(GLOBAL_STATE_URL_KEY);
const urlProfileState =
urlStateStorage.get<DiscoverProfileUrlState>(PROFILE_STATE_URL_KEY) ?? undefined;
const urlAppState = {
...tabInitialAppState,
...(defaultUrlState ??
cleanupUrlState(urlStateStorage.get<AppStateUrl>(APP_STATE_URL_KEY), services.uiSettings)),
};

dispatch(
internalStateSlice.actions.setInitialProfileUrlState({
tabId,
initialProfileUrlState: urlProfileState,
})
);

const discoverTabLoadTracker = scopedEbtManager$
.getValue()
.trackPerformanceEvent('discoverLoadSavedSearch');
Expand Down
Loading
Loading