Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

Fix: Preserve query on navigation b/w views | Logs Explorer code cleanup (#9496)

Aditya Singh2f4e371dac3a
diff --git a/frontend/src/container/ExplorerOptions/ExplorerOptionWrapper.tsx b/frontend/src/container/ExplorerOptions/ExplorerOptionWrapper.tsx
index a2ecfce579..9115e1ca66 100644
--- a/frontend/src/container/ExplorerOptions/ExplorerOptionWrapper.tsx
+++ b/frontend/src/container/ExplorerOptions/ExplorerOptionWrapper.tsx
@@ -17,6 +17,7 @@ function ExplorerOptionWrapper({
isOneChartPerQuery,
splitedQueries,
signalSource,
+ handleChangeSelectedView,
}: ExplorerOptionsWrapperProps): JSX.Element {
const [isExplorerOptionHidden, setIsExplorerOptionHidden] = useState(false);
@@ -38,6 +39,7 @@ function ExplorerOptionWrapper({
setIsExplorerOptionHidden={setIsExplorerOptionHidden}
isOneChartPerQuery={isOneChartPerQuery}
splitedQueries={splitedQueries}
+ handleChangeSelectedView={handleChangeSelectedView}
/>
);
}
diff --git a/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx b/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx
index d425b29d4d..9b59f5fad1 100644
--- a/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx
+++ b/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx
@@ -72,10 +72,11 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { ViewProps } from 'types/api/saveViews/types';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
+import { panelTypeToExplorerView } from 'utils/explorerUtils';
import { PreservedViewsTypes } from './constants';
import ExplorerOptionsHideArea from './ExplorerOptionsHideArea';
-import { PreservedViewsInLocalStorage } from './types';
+import { ChangeViewFunctionType, PreservedViewsInLocalStorage } from './types';
import {
DATASOURCE_VS_ROUTES,
generateRGBAFromHex,
@@ -98,6 +99,7 @@ function ExplorerOptions({
setIsExplorerOptionHidden,
isOneChartPerQuery = false,
splitedQueries = [],
+ handleChangeSelectedView,
}: ExplorerOptionsProps): JSX.Element {
const [isExport, setIsExport] = useState<boolean>(false);
const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
@@ -412,13 +414,22 @@ function ExplorerOptions({
if (!currentViewDetails) return;
const { query, name, id, panelType: currentPanelType } = currentViewDetails;
- handleExplorerTabChange(currentPanelType, {
- query,
- name,
- id,
- });
+ if (handleChangeSelectedView) {
+ handleChangeSelectedView(panelTypeToExplorerView[currentPanelType], {
+ query,
+ name,
+ id,
+ });
+ } else {
+ // to remove this after traces cleanup
+ handleExplorerTabChange(currentPanelType, {
+ query,
+ name,
+ id,
+ });
+ }
},
- [viewsData, handleExplorerTabChange],
+ [viewsData, handleExplorerTabChange, handleChangeSelectedView],
);
const updatePreservedViewInLocalStorage = (option: {
@@ -524,6 +535,10 @@ function ExplorerOptions({
return;
}
+ if (handleChangeSelectedView) {
+ handleChangeSelectedView(panelTypeToExplorerView[PANEL_TYPES.LIST]);
+ }
+
history.replace(DATASOURCE_VS_ROUTES[sourcepage]);
};
@@ -1020,6 +1035,7 @@ export interface ExplorerOptionsProps {
setIsExplorerOptionHidden?: Dispatch<SetStateAction<boolean>>;
isOneChartPerQuery?: boolean;
splitedQueries?: Query[];
+ handleChangeSelectedView?: ChangeViewFunctionType;
}
ExplorerOptions.defaultProps = {
@@ -1029,6 +1045,7 @@ ExplorerOptions.defaultProps = {
isOneChartPerQuery: false,
splitedQueries: [],
signalSource: '',
+ handleChangeSelectedView: undefined,
};
export default ExplorerOptions;
diff --git a/frontend/src/container/ExplorerOptions/types.ts b/frontend/src/container/ExplorerOptions/types.ts
index 3f8fec9661..0f12a621ea 100644
--- a/frontend/src/container/ExplorerOptions/types.ts
+++ b/frontend/src/container/ExplorerOptions/types.ts
@@ -2,6 +2,8 @@ import { NotificationInstance } from 'antd/es/notification/interface';
import { AxiosResponse } from 'axios';
import { SaveViewWithNameProps } from 'components/ExplorerCard/types';
import { PANEL_TYPES } from 'constants/queryBuilder';
+import { ICurrentQueryData } from 'hooks/useHandleExplorerTabChange';
+import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { Dispatch, SetStateAction } from 'react';
import { UseMutateAsyncFunction } from 'react-query';
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
@@ -38,3 +40,8 @@ export type PreservedViewType =
export type PreservedViewsInLocalStorage = Partial<
Record<PreservedViewType, { key: string; value: string }>
>;
+
+export type ChangeViewFunctionType = (
+ view: ExplorerViews,
+ querySearchParameters?: ICurrentQueryData,
+) => void;
diff --git a/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx b/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
index f30864174c..de73bb9006 100644
--- a/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
+++ b/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
@@ -6,7 +6,6 @@ import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQuery
import { logsQueryRangeEmptyResponse } from 'mocks-server/__mockdata__/logs_query_range';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
-import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import { QueryBuilderContext } from 'providers/QueryBuilder';
import { render, screen } from 'tests/test-utils';
@@ -122,12 +121,12 @@ describe('LogsExplorerList - empty states', () => {
<QueryBuilderContext.Provider value={mockTraceToLogsContextValue as any}>
<PreferenceContextProvider>
<LogsExplorerViews
- selectedView={ExplorerViews.LIST}
setIsLoadingQueries={(): void => {}}
listQueryKeyRef={{ current: {} }}
chartQueryKeyRef={{ current: {} }}
setWarning={(): void => {}}
showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
/>
</PreferenceContextProvider>
</QueryBuilderContext.Provider>,
@@ -187,12 +186,12 @@ describe('LogsExplorerList - empty states', () => {
<QueryBuilderContext.Provider value={mockTraceToLogsContextValue as any}>
<PreferenceContextProvider>
<LogsExplorerViews
- selectedView={ExplorerViews.LIST}
setIsLoadingQueries={(): void => {}}
listQueryKeyRef={{ current: {} }}
chartQueryKeyRef={{ current: {} }}
setWarning={(): void => {}}
showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
/>
</PreferenceContextProvider>
</QueryBuilderContext.Provider>,
diff --git a/frontend/src/container/LogsExplorerViews/explorerUtils.ts b/frontend/src/container/LogsExplorerViews/explorerUtils.ts
new file mode 100644
index 0000000000..81897002c7
--- /dev/null
+++ b/frontend/src/container/LogsExplorerViews/explorerUtils.ts
@@ -0,0 +1,210 @@
+import {
+ initialQueryBuilderFormValues,
+ OPERATORS,
+ PANEL_TYPES,
+} from 'constants/queryBuilder';
+import { getPaginationQueryDataV2 } from 'lib/newQueryBuilder/getPaginationQueryData';
+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
+import {
+ IBuilderQuery,
+ Query,
+ TagFilter,
+} from 'types/api/queryBuilder/queryBuilderData';
+import { Filter } from 'types/api/v5/queryRange';
+import { LogsAggregatorOperator } from 'types/common/queryBuilder';
+import { v4 } from 'uuid';
+
+export const getListQuery = (
+ stagedQuery: Query | null,
+): IBuilderQuery | null => {
+ if (!stagedQuery || stagedQuery.builder.queryData.length < 1) return null;
+
+ return stagedQuery.builder.queryData[0] ?? null;
+};
+
+export const getFrequencyChartData = (
+ stagedQuery: Query | null,
+ activeLogId: string | null,
+): Query | null => {
+ if (!stagedQuery) {
+ return null;
+ }
+ const baseFirstQuery = getListQuery(stagedQuery);
+
+ if (!baseFirstQuery) {
+ return null;
+ }
+
+ let updatedFilterExpression = baseFirstQuery.filter?.expression || '';
+ if (activeLogId) {
+ updatedFilterExpression = `${updatedFilterExpression} id <= '${activeLogId}'`.trim();
+ }
+
+ const modifiedQueryData: IBuilderQuery = {
+ ...baseFirstQuery,
+ disabled: false,
+ aggregateOperator: LogsAggregatorOperator.COUNT,
+ filter: {
+ ...baseFirstQuery.filter,
+ expression: updatedFilterExpression || '',
+ },
+ ...(activeLogId && {
+ filters: {
+ ...baseFirstQuery.filters,
+ items: [
+ ...(baseFirstQuery?.filters?.items || []),
+ {
+ id: v4(),
+ key: {
+ key: 'id',
+ type: '',
+ dataType: DataTypes.String,
+ },
+ op: OPERATORS['<='],
+ value: activeLogId,
+ },
+ ],
+ op: 'AND',
+ },
+ }),
+ groupBy: [
+ {
+ key: 'severity_text',
+ dataType: DataTypes.String,
+ type: '',
+ id: 'severity_text--string----true',
+ },
+ ],
+ legend: '{{severity_text}}',
+ orderBy: [],
+ having: {
+ expression: '',
+ },
+ };
+
+ const modifiedQuery: Query = {
+ ...stagedQuery,
+ builder: {
+ ...stagedQuery.builder,
+ queryData: [modifiedQueryData], // single query data required for list chart
+ },
+ };
+
+ return modifiedQuery;
+};
+
+export const getQueryByPanelType = (
+ query: Query | null,
+ selectedPanelType: PANEL_TYPES,
+ params: {
+ page?: number;
+ pageSize?: number;
+ filters?: TagFilter;
+ filter?: Filter;
+ activeLogId?: string | null;
+ orderBy?: string;
+ },
+): Query | null => {
+ if (!query) return null;
+
+ let queryData: IBuilderQuery[] = query.builder.queryData.map((item) => ({
+ ...item,
+ }));
+
+ if (selectedPanelType === PANEL_TYPES.LIST) {
+ const { activeLogId = null, orderBy = 'timestamp:desc' } = params;
+
+ const paginateData = getPaginationQueryDataV2({
+ page: params.page ?? 1,
+ pageSize: params.pageSize ?? 10,
+ });
+
+ let updatedFilters = params.filters;
+ let updatedFilterExpression = params.filter?.expression || '';
+ if (activeLogId) {
+ updatedFilters = {
+ ...params.filters,
+ items: [
+ ...(params.filters?.items || []),
+ {
+ id: v4(),
+ key: {
+ key: 'id',
+ type: '',
+ dataType: DataTypes.String,
+ },
+ op: OPERATORS['<='],
+ value: activeLogId,
+ },
+ ],
+ op: 'AND',
+ };
+ updatedFilterExpression = `${updatedFilterExpression} id <= '${activeLogId}'`.trim();
+ }
+
+ // Create orderBy array based on orderDirection
+ const [columnName, order] = orderBy.split(':');
+
+ const newOrderBy = [
+ { columnName: columnName || 'timestamp', order: order || 'desc' },
+ { columnName: 'id', order: order || 'desc' },
+ ];
+
+ queryData = [
+ {
+ ...(getListQuery(query) || initialQueryBuilderFormValues),
+ ...paginateData,
+ ...(updatedFilters ? { filters: updatedFilters } : {}),
+ filter: { expression: updatedFilterExpression || '' },
+ groupBy: [],
+ having: {
+ expression: '',
+ },
+ orderBy: newOrderBy,
+ disabled: false,
+ },
+ ];
+ }
+
+ const data: Query = {
+ ...query,
+ builder: {
+ ...query.builder,
+ queryData,
+ },
+ };
+
+ return data;
+};
+
+export const getExportQueryData = (
+ query: Query | null,
+ panelType: PANEL_TYPES,
+): Query | null => {
+ if (!query) return null;
+
+ if (panelType === PANEL_TYPES.LIST) {
+ const listQuery = getListQuery(query);
+ if (!listQuery) return null;
+
+ return {
+ ...query,
+ builder: {
+ ...query.builder,
+ queryData: [
+ {
+ ...listQuery,
+ orderBy: [
+ {
+ columnName: 'timestamp',
+ order: 'desc',
+ },
+ ],
+ limit: null,
+ },
+ ],
+ },
+ };
+ }
+ return query;
+};
diff --git a/frontend/src/container/LogsExplorerViews/index.tsx b/frontend/src/container/LogsExplorerViews/index.tsx
index 291ce227b3..6798577b2d 100644
--- a/frontend/src/container/LogsExplorerViews/index.tsx
+++ b/frontend/src/container/LogsExplorerViews/index.tsx
@@ -11,29 +11,29 @@ import { QueryParams } from 'constants/query';
import {
initialFilters,
initialQueriesMap,
- initialQueryBuilderFormValues,
- OPERATORS,
PANEL_TYPES,
} from 'constants/queryBuilder';
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
+import { ChangeViewFunctionType } from 'container/ExplorerOptions/types';
import GoToTop from 'container/GoToTop';
-import {} from 'container/LiveLogs/constants';
import LogsExplorerChart from 'container/LogsExplorerChart';
import LogsExplorerList from 'container/LogsExplorerList';
import LogsExplorerTable from 'container/LogsExplorerTable';
+import {
+ getExportQueryData,
+ getFrequencyChartData,
+ getListQuery,
+ getQueryByPanelType,
+} from 'container/LogsExplorerViews/explorerUtils';
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
-import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQueryData from 'hooks/useUrlQueryData';
-import { getPaginationQueryDataV2 } from 'lib/newQueryBuilder/getPaginationQueryData';
-import { cloneDeep, defaultTo, isEmpty, isUndefined, set } from 'lodash-es';
+import { isEmpty, isUndefined } from 'lodash-es';
import LiveLogs from 'pages/LiveLogs';
-import { ExplorerViews } from 'pages/LogsExplorer/utils';
import {
Dispatch,
memo,
@@ -52,15 +52,10 @@ import { Warning } from 'types/api';
import { Dashboard } from 'types/api/dashboard/getAll';
import APIError from 'types/api/error';
import { ILog } from 'types/api/logs/log';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- Query,
- TagFilter,
-} from 'types/api/queryBuilder/queryBuilderData';
+import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { Filter } from 'types/api/v5/queryRange';
import { QueryDataV3 } from 'types/api/widgets/getQuery';
-import { DataSource, LogsAggregatorOperator } from 'types/common/queryBuilder';
+import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';
import { v4 } from 'uuid';
@@ -68,14 +63,13 @@ import { v4 } from 'uuid';
import LogsActionsContainer from './LogsActionsContainer';
function LogsExplorerViewsContainer({
- selectedView,
setIsLoadingQueries,
listQueryKeyRef,
chartQueryKeyRef,
setWarning,
showLiveLogs,
+ handleChangeSelectedView,
}: {
- selectedView: ExplorerViews;
setIsLoadingQueries: React.Dispatch<React.SetStateAction<boolean>>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
listQueryKeyRef: MutableRefObject<any>;
@@ -83,19 +77,14 @@ function LogsExplorerViewsContainer({
chartQueryKeyRef: MutableRefObject<any>;
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
showLiveLogs: boolean;
+ handleChangeSelectedView: ChangeViewFunctionType;
}): JSX.Element {
const { safeNavigate } = useSafeNavigate();
const dispatch = useDispatch();
- const [showFrequencyChart, setShowFrequencyChart] = useState(false);
-
- useEffect(() => {
- const frequencyChart = getFromLocalstorage(LOCALSTORAGE.SHOW_FREQUENCY_CHART);
- setShowFrequencyChart(frequencyChart === 'true');
- }, []);
-
- // this is to respect the panel type present in the URL rather than defaulting it to list always.
- const panelTypes = useGetPanelTypesQueryParam(PANEL_TYPES.LIST);
+ const [showFrequencyChart, setShowFrequencyChart] = useState(
+ () => getFromLocalstorage(LOCALSTORAGE.SHOW_FREQUENCY_CHART) === 'true',
+ );
const { activeLogId } = useCopyLogLink();
@@ -117,14 +106,9 @@ function LogsExplorerViewsContainer({
stagedQuery,
panelType,
updateAllQueriesOperators,
- handleSetConfig,
} = useQueryBuilder();
- const [selectedPanelType, setSelectedPanelType] = useState<PANEL_TYPES>(
- panelType || PANEL_TYPES.LIST,
- );
-
- const { handleExplorerTabChange } = useHandleExplorerTabChange();
+ const selectedPanelType = panelType || PANEL_TYPES.LIST;
// State
const [page, setPage] = useState<number>(1);
@@ -135,27 +119,9 @@ function LogsExplorerViewsContainer({
const [orderBy, setOrderBy] = useState<string>('timestamp:desc');
- const listQuery = useMemo(() => {
- if (!stagedQuery || stagedQuery.builder.queryData.length < 1) return null;
-
- return stagedQuery.builder.queryData.find((item) => !item.disabled) || null;
- }, [stagedQuery]);
-
- const isMultipleQueries = useMemo(
- () =>
- currentQuery?.builder?.queryData?.length > 1 ||
- currentQuery?.builder?.queryFormulas?.length > 0,
- [currentQuery],
- );
-
- const isGroupByExist = useMemo(() => {
- const groupByCount: number = currentQuery?.builder?.queryData?.reduce<number>(
- (acc, query) => acc + query.groupBy.length,
- 0,
- );
-
- return groupByCount > 0;
- }, [currentQuery]);
+ const listQuery = useMemo(() => getListQuery(stagedQuery) || null, [
+ stagedQuery,
+ ]);
const isLimit: boolean = useMemo(() => {
if (!listQuery) return false;
@@ -165,66 +131,9 @@ function LogsExplorerViewsContainer({
}, [logs.length, listQuery]);
useEffect(() => {
- if (!stagedQuery || !listQuery) {
- setListChartQuery(null);
- return;
- }
-
- let updatedFilterExpression = listQuery.filter?.expression || '';
- if (activeLogId) {
- updatedFilterExpression = `${updatedFilterExpression} id <= '${activeLogId}'`.trim();
- }
-
- const modifiedQueryData: IBuilderQuery = {
- ...listQuery,
- aggregateOperator: LogsAggregatorOperator.COUNT,
- groupBy: [
- {
- key: 'severity_text',
- dataType: DataTypes.String,
- type: '',
- id: 'severity_text--string----true',
- },
- ],
- legend: '{{severity_text}}',
- filter: {
- ...listQuery?.filter,
- expression: updatedFilterExpression || '',
- },
- ...(activeLogId && {
- filters: {
- ...listQuery?.filters,
- items: [
- ...(listQuery?.filters?.items || []),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- },
- op: OPERATORS['<='],
- value: activeLogId,
- },
- ],
- op: 'AND',
- },
- }),
- };
-
- const modifiedQuery: Query = {
- ...stagedQuery,
- builder: {
- ...stagedQuery.builder,
- queryData: stagedQuery.builder.queryData.map((item) => ({
- ...item,
- ...modifiedQueryData,
- })),
- },
- };
-
+ const modifiedQuery = getFrequencyChartData(stagedQuery, activeLogId);
setListChartQuery(modifiedQuery);
- }, [stagedQuery, listQuery, activeLogId]);
+ }, [stagedQuery, activeLogId]);
const exportDefaultQuery = useMemo(
() =>
@@ -246,7 +155,9 @@ function LogsExplorerViewsContainer({
ENTITY_VERSION_V5,
{
enabled:
- showFrequencyChart && !!listChartQuery && panelType === PANEL_TYPES.LIST,
+ showFrequencyChart &&
+ !!listChartQuery &&
+ selectedPanelType === PANEL_TYPES.LIST,
},
{},
undefined,
@@ -264,7 +175,7 @@ function LogsExplorerViewsContainer({
error,
} = useGetExplorerQueryRange(
requestData,
- panelType,
+ selectedPanelType,
ENTITY_VERSION_V5,
{
keepPreviousData: true,
@@ -296,77 +207,13 @@ function LogsExplorerViewsContainer({
filters: TagFilter;
filter: Filter;
},
- ): Query | null => {
- if (!query) return null;
-
- const paginateData = getPaginationQueryDataV2({
- page: params.page,
- pageSize: params.pageSize,
- });
-
- // Add filter for activeLogId if present
- let updatedFilters = params.filters;
- let updatedFilterExpression = params.filter?.expression || '';
- if (activeLogId) {
- updatedFilters = {
- ...params.filters,
- items: [
- ...(params.filters?.items || []),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- },
- op: OPERATORS['<='],
- value: activeLogId,
- },
- ],
- op: 'AND',
- };
- updatedFilterExpression = `${updatedFilterExpression} id <= '${activeLogId}'`.trim();
- }
-
- // Create orderBy array based on orderDirection
- const [columnName, order] = orderBy.split(':');
-
- const newOrderBy = [
- { columnName: columnName || 'timestamp', order: order || 'desc' },
- { columnName: 'id', order: order || 'desc' },
- ];
-
- const queryData: IBuilderQuery[] =
- query.builder.queryData.length > 1
- ? query.builder.queryData.map((item) => ({
- ...item,
- ...(selectedView !== ExplorerViews.LIST ? { order: [] } : {}),
- }))
- : [
- {
- ...(listQuery || initialQueryBuilderFormValues),
- ...paginateData,
- ...(updatedFilters ? { filters: updatedFilters } : {}),
- filter: {
- expression: updatedFilterExpression || '',
- },
- ...(selectedView === ExplorerViews.LIST
- ? { order: newOrderBy, orderBy: newOrderBy }
- : { order: [] }),
- },
- ];
-
- const data: Query = {
- ...query,
- builder: {
- ...query.builder,
- queryData,
- },
- };
-
- return data;
- },
- [activeLogId, orderBy, listQuery, selectedView],
+ ): Query | null =>
+ getQueryByPanelType(query, selectedPanelType, {
+ ...params,
+ activeLogId,
+ orderBy,
+ }),
+ [activeLogId, orderBy, selectedPanelType],
);
useEffect(() => {
@@ -412,7 +259,7 @@ function LogsExplorerViewsContainer({
if (!logEventCalledRef.current && !isUndefined(data?.payload)) {
const currentData = data?.payload?.data?.newResult?.data?.result || [];
logEvent('Logs Explorer: Page visited', {
- panelType,
+ panelType: selectedPanelType,
isEmpty: !currentData?.[0]?.list,
});
logEventCalledRef.current = true;
@@ -420,31 +267,24 @@ function LogsExplorerViewsContainer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data?.payload]);
- const getUpdatedQueryForExport = useCallback((): Query => {
- const updatedQuery = cloneDeep(currentQuery);
-
- set(updatedQuery, 'builder.queryData[0].pageSize', 10);
-
- return updatedQuery;
- }, [currentQuery]);
-
const handleExport = useCallback(
(dashboard: Dashboard | null, isNewDashboard?: boolean): void => {
- if (!dashboard || !panelType) return;
+ if (!dashboard || !selectedPanelType) return;
- const panelTypeParam = AVAILABLE_EXPORT_PANEL_TYPES.includes(panelType)
- ? panelType
+ const panelTypeParam = AVAILABLE_EXPORT_PANEL_TYPES.includes(
+ selectedPanelType,
+ )
+ ? selectedPanelType
: PANEL_TYPES.TIME_SERIES;
const widgetId = v4();
- const query =
- panelType === PANEL_TYPES.LIST
- ? getUpdatedQueryForExport()
- : exportDefaultQuery;
+ const query = getExportQueryData(requestData, selectedPanelType);
+
+ if (!query) return;
logEvent('Logs Explorer: Add to dashboard successful', {
- panelType,
+ panelType: selectedPanelType,
isNewDashboard,
dashboardName: dashboard?.data?.title,
});
@@ -458,36 +298,9 @@ function LogsExplorerViewsContainer({
safeNavigate(dashboardEditView);
},
- [getUpdatedQueryForExport, exportDefaultQuery, safeNavigate, panelType],
+ [safeNavigate, requestData, selectedPanelType],
);
- useEffect(() => {
- const shouldChangeView = isMultipleQueries || isGroupByExist;
-
- if (selectedPanelType === PANEL_TYPES.LIST && shouldChangeView) {
- handleExplorerTabChange(PANEL_TYPES.TIME_SERIES);
- setSelectedPanelType(PANEL_TYPES.TIME_SERIES);
- }
-
- if (panelType) {
- setSelectedPanelType(panelType);
- }
- }, [
- isMultipleQueries,
- isGroupByExist,
- selectedPanelType,
- selectedView,
- handleExplorerTabChange,
- panelType,
- ]);
-
- useEffect(() => {
- if (selectedView && selectedView === ExplorerViews.LIST && handleSetConfig) {
- handleSetConfig(defaultTo(panelTypes, PANEL_TYPES.LIST), DataSource.LOGS);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [handleSetConfig, panelTypes]);
-
useEffect(() => {
const currentData = data?.payload?.data?.newResult?.data?.result || [];
if (currentData.length > 0 && currentData[0].list) {
@@ -546,19 +359,17 @@ function LogsExplorerViewsContainer({
pageSize,
minTime,
activeLogId,
- panelType,
- selectedView,
+ selectedPanelType,
dispatch,
selectedTime,
maxTime,
orderBy,
- selectedPanelType,
]);
const chartData = useMemo(() => {
if (!stagedQuery) return [];
- if (panelType === PANEL_TYPES.LIST) {
+ if (selectedPanelType === PANEL_TYPES.LIST) {
if (listChartData && listChartData.payload.data?.result.length > 0) {
return listChartData.payload.data.result;
}
@@ -578,7 +389,7 @@ function LogsExplorerViewsContainer({
const firstPayloadQueryArray = firstPayloadQuery ? [firstPayloadQuery] : [];
return isGroupByExist ? data.payload.data.result : firstPayloadQueryArray;
- }, [stagedQuery, panelType, data, listChartData, listQuery]);
+ }, [stagedQuery, selectedPanelType, data, listChartData, listQuery]);
useEffect(() => {
if (
@@ -639,7 +450,7 @@ function LogsExplorerViewsContainer({
className="logs-frequency-chart"
isLoading={isFetchingListChartData || isLoadingListChartData}
data={chartData}
- isLogsExplorerViews={panelType === PANEL_TYPES.LIST}
+ isLogsExplorerViews={selectedPanelType === PANEL_TYPES.LIST}
/>
</div>
)}
@@ -695,6 +506,7 @@ function LogsExplorerViewsContainer({
query={exportDefaultQuery}
onExport={handleExport}
sourcepage={DataSource.LOGS}
+ handleChangeSelectedView={handleChangeSelectedView}
/>
</div>
);
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
index 687fad387d..698e0df4b5 100644
--- a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
@@ -5,12 +5,12 @@ import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQuery
import { logsQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
-import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import { QueryBuilderContext } from 'providers/QueryBuilder';
import { VirtuosoMockContext } from 'react-virtuoso';
import { fireEvent, render, RenderResult, waitFor } from 'tests/test-utils';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
+import { LogsAggregatorOperator } from 'types/common/queryBuilder';
import LogsExplorerViews from '..';
import {
@@ -152,12 +152,12 @@ const renderer = (): RenderResult =>
>
<PreferenceContextProvider>
<LogsExplorerViews
- selectedView={ExplorerViews.LIST}
setIsLoadingQueries={(): void => {}}
listQueryKeyRef={{ current: {} }}
chartQueryKeyRef={{ current: {} }}
setWarning={(): void => {}}
showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
/>
</PreferenceContextProvider>
</VirtuosoMockContext.Provider>,
@@ -218,12 +218,12 @@ describe('LogsExplorerViews -', () => {
<QueryBuilderContext.Provider value={mockQueryBuilderContextValue}>
<PreferenceContextProvider>
<LogsExplorerViews
- selectedView={ExplorerViews.LIST}
setIsLoadingQueries={(): void => {}}
listQueryKeyRef={{ current: {} }}
chartQueryKeyRef={{ current: {} }}
setWarning={(): void => {}}
showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
/>
</PreferenceContextProvider>
</QueryBuilderContext.Provider>,
@@ -295,12 +295,12 @@ describe('LogsExplorerViews -', () => {
<QueryBuilderContext.Provider value={customContext as any}>
<PreferenceContextProvider>
<LogsExplorerViews
- selectedView={ExplorerViews.LIST}
setIsLoadingQueries={(): void => {}}
listQueryKeyRef={{ current: {} }}
chartQueryKeyRef={{ current: {} }}
setWarning={(): void => {}}
showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
/>
</PreferenceContextProvider>
</QueryBuilderContext.Provider>,
@@ -323,4 +323,120 @@ describe('LogsExplorerViews -', () => {
}
});
});
+
+ describe('Queries by View', () => {
+ it('builds Frequency Chart query with COUNT and severity_text grouping and activeLogId bound', async () => {
+ // Enable frequency chart via localstorage and provide activeLogId
+ (useCopyLogLink as jest.Mock).mockReturnValue({
+ activeLogId: ACTIVE_LOG_ID,
+ });
+ // Ensure default mock return exists
+ (useGetExplorerQueryRange as jest.Mock).mockReturnValue({
+ data: { payload: logsQueryRangeSuccessNewFormatResponse },
+ });
+
+ // Render with LIST panel type so the frequency chart hook runs with TIME_SERIES
+ render(
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 300, itemHeight: 100 }}
+ >
+ <PreferenceContextProvider>
+ <QueryBuilderContext.Provider
+ value={
+ { ...mockQueryBuilderContextValue, panelType: PANEL_TYPES.LIST } as any
+ }
+ >
+ <LogsExplorerViews
+ setIsLoadingQueries={(): void => {}}
+ listQueryKeyRef={{ current: {} }}
+ chartQueryKeyRef={{ current: {} }}
+ setWarning={(): void => {}}
+ showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
+ />
+ </QueryBuilderContext.Provider>
+ </PreferenceContextProvider>
+ </VirtuosoMockContext.Provider>,
+ );
+
+ await waitFor(() => {
+ const chartCall = (useGetExplorerQueryRange as jest.Mock).mock.calls.find(
+ (call) => call[1] === PANEL_TYPES.TIME_SERIES && call[0],
+ );
+ expect(chartCall).toBeDefined();
+ if (chartCall) {
+ const frequencyQuery = chartCall[0];
+ const first = frequencyQuery.builder.queryData[0];
+ // Panel type used for chart fetch
+ expect(chartCall[1]).toBe(PANEL_TYPES.TIME_SERIES);
+ // Transformations
+ expect(first.aggregateOperator).toBe(LogsAggregatorOperator.COUNT);
+ expect(first.groupBy?.[0]?.key).toBe('severity_text');
+ expect(first.legend).toBe('{{severity_text}}');
+ expect(Array.isArray(first.orderBy) && first.orderBy.length === 0).toBe(
+ true,
+ );
+ expect(first.having?.expression).toBe('');
+ // activeLogId constraints
+ expect(first.filter?.expression).toContain(`id <= '${ACTIVE_LOG_ID}'`);
+ expect(
+ first.filters?.items?.some(
+ (it: any) =>
+ it.key?.key === 'id' && it.op === '<=' && it.value === ACTIVE_LOG_ID,
+ ),
+ ).toBe(true);
+ }
+ });
+ });
+
+ it('builds List View query with orderBy and clears groupBy/having', async () => {
+ (useCopyLogLink as jest.Mock).mockReturnValue({ activeLogId: undefined });
+ (useGetExplorerQueryRange as jest.Mock).mockReturnValue({
+ data: { payload: logsQueryRangeSuccessNewFormatResponse },
+ });
+
+ render(
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 300, itemHeight: 100 }}
+ >
+ <PreferenceContextProvider>
+ <QueryBuilderContext.Provider
+ value={
+ { ...mockQueryBuilderContextValue, panelType: PANEL_TYPES.LIST } as any
+ }
+ >
+ <LogsExplorerViews
+ setIsLoadingQueries={(): void => {}}
+ listQueryKeyRef={{ current: {} }}
+ chartQueryKeyRef={{ current: {} }}
+ setWarning={(): void => {}}
+ showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
+ />
+ </QueryBuilderContext.Provider>
+ </PreferenceContextProvider>
+ </VirtuosoMockContext.Provider>,
+ );
+
+ await waitFor(() => {
+ const listCall = (useGetExplorerQueryRange as jest.Mock).mock.calls.find(
+ (call) => call[1] === PANEL_TYPES.LIST && call[0],
+ );
+ expect(listCall).toBeDefined();
+ if (listCall) {
+ const listQueryArg = listCall[0];
+ const first = listQueryArg.builder.queryData[0];
+ expect(first.groupBy?.length ?? 0).toBe(0);
+ expect(first.having?.expression).toBe('');
+ // Default orderBy should be timestamp desc, then id desc
+ expect(first.orderBy).toEqual([
+ { columnName: 'timestamp', order: 'desc' },
+ { columnName: 'id', order: 'desc' },
+ ]);
+ // Ensure the query is enabled for fetch
+ expect(first.disabled).toBe(false);
+ }
+ });
+ });
+ });
});
diff --git a/frontend/src/hooks/useHandleExplorerTabChange.ts b/frontend/src/hooks/useHandleExplorerTabChange.ts
index cf06337867..88f95ae08b 100644
--- a/frontend/src/hooks/useHandleExplorerTabChange.ts
+++ b/frontend/src/hooks/useHandleExplorerTabChange.ts
@@ -9,6 +9,12 @@ import { DataSource } from 'types/common/queryBuilder';
import { useGetSearchQueryParam } from './queryBuilder/useGetSearchQueryParam';
import { useQueryBuilder } from './queryBuilder/useQueryBuilder';
+export interface ICurrentQueryData {
+ name: string;
+ id: string;
+ query: Query;
+}
+
export const useHandleExplorerTabChange = (): {
handleExplorerTabChange: (
type: string,
@@ -87,9 +93,3 @@ export const useHandleExplorerTabChange = (): {
return { handleExplorerTabChange };
};
-
-interface ICurrentQueryData {
- name: string;
- id: string;
- query: Query;
-}
diff --git a/frontend/src/pages/LogsExplorer/index.tsx b/frontend/src/pages/LogsExplorer/index.tsx
index e37a3e63a6..e4da7619ca 100644
--- a/frontend/src/pages/LogsExplorer/index.tsx
+++ b/frontend/src/pages/LogsExplorer/index.tsx
@@ -10,8 +10,7 @@ import QuickFilters from 'components/QuickFilters/QuickFilters';
import { QuickFiltersSource, SignalType } from 'components/QuickFilters/types';
import WarningPopover from 'components/WarningPopover/WarningPopover';
import { LOCALSTORAGE } from 'constants/localStorage';
-import { QueryParams } from 'constants/query';
-import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
+import { PANEL_TYPES } from 'constants/queryBuilder';
import LogExplorerQuerySection from 'container/LogExplorerQuerySection';
import LogsExplorerViewsContainer from 'container/LogsExplorerViews';
import {
@@ -25,34 +24,33 @@ import RightToolbarActions from 'container/QueryBuilder/components/ToolbarAction
import Toolbar from 'container/Toolbar/Toolbar';
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
-import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
+import {
+ ICurrentQueryData,
+ useHandleExplorerTabChange,
+} from 'hooks/useHandleExplorerTabChange';
import useUrlQueryData from 'hooks/useUrlQueryData';
-import { isEmpty, isEqual, isNull } from 'lodash-es';
+import { defaultTo, isEmpty, isEqual, isNull } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { EventSourceProvider } from 'providers/EventSource';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useSearchParams } from 'react-router-dom-v5-compat';
import { Warning } from 'types/api';
-import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
- getExplorerViewForPanelType,
- getExplorerViewFromUrl,
+ explorerViewToPanelType,
+ panelTypeToExplorerView,
} from 'utils/explorerUtils';
import { ExplorerViews } from './utils';
function LogsExplorer(): JSX.Element {
- const [searchParams] = useSearchParams();
const [showLiveLogs, setShowLiveLogs] = useState<boolean>(false);
// Get panel type from URL
const panelTypesFromUrl = useGetPanelTypesQueryParam(PANEL_TYPES.LIST);
- const [selectedView, setSelectedView] = useState<ExplorerViews>(() =>
- getExplorerViewFromUrl(searchParams, panelTypesFromUrl),
+ const [selectedView, setSelectedView] = useState<ExplorerViews>(
+ () => panelTypeToExplorerView[panelTypesFromUrl],
);
const { logs } = usePreferenceContext();
const { preferences } = logs;
@@ -67,30 +65,7 @@ function LogsExplorer(): JSX.Element {
return true;
});
- // Update selected view when panel type from URL changes
- useEffect(() => {
- if (panelTypesFromUrl) {
- const newView = getExplorerViewForPanelType(panelTypesFromUrl);
- if (newView && newView !== selectedView) {
- setSelectedView(newView);
- }
- }
- }, [panelTypesFromUrl, selectedView]);
-
- // Update URL when selectedView changes (without triggering re-renders)
- useEffect(() => {
- const url = new URL(window.location.href);
- url.searchParams.set(QueryParams.selectedExplorerView, selectedView);
- window.history.replaceState({}, '', url.toString());
- }, [selectedView]);
-
- const {
- handleRunQuery,
- handleSetConfig,
- updateAllQueriesOperators,
- currentQuery,
- updateQueriesData,
- } = useQueryBuilder();
+ const { handleRunQuery, handleSetConfig } = useQueryBuilder();
const { handleExplorerTabChange } = useHandleExplorerTabChange();
@@ -102,49 +77,12 @@ function LogsExplorer(): JSX.Element {
const [warning, setWarning] = useState<Warning | undefined>(undefined);
- const [shouldReset, setShouldReset] = useState(false);
-
- const [defaultQuery, setDefaultQuery] = useState<Query>(() =>
- updateAllQueriesOperators(
- initialQueriesMap.logs,
- PANEL_TYPES.LIST,
- DataSource.LOGS,
- ),
- );
-
const handleChangeSelectedView = useCallback(
- (view: ExplorerViews): void => {
- if (selectedView === ExplorerViews.LIST) {
- handleSetConfig(PANEL_TYPES.LIST, DataSource.LOGS);
- }
-
- if (view === ExplorerViews.LIST) {
- if (
- selectedView !== ExplorerViews.LIST &&
- currentQuery?.builder?.queryData?.[0]
- ) {
- const filterToRetain = currentQuery.builder.queryData[0].filter;
-
- const newDefaultQuery = updateAllQueriesOperators(
- initialQueriesMap.logs,
- PANEL_TYPES.LIST,
- DataSource.LOGS,
- );
-
- const newListQuery = updateQueriesData(
- newDefaultQuery,
- 'queryData',
- (item, index) => {
- if (index === 0) {
- return { ...item, filter: filterToRetain };
- }
- return item;
- },
- );
- setDefaultQuery(newListQuery);
- }
- setShouldReset(true);
- }
+ (view: ExplorerViews, querySearchParameters?: ICurrentQueryData): void => {
+ handleSetConfig(
+ defaultTo(explorerViewToPanelType[view], PANEL_TYPES.LIST),
+ DataSource.LOGS,
+ );
setSelectedView(view);
@@ -153,38 +91,13 @@ function LogsExplorer(): JSX.Element {
}
handleExplorerTabChange(
- view === ExplorerViews.TIMESERIES ? PANEL_TYPES.TIME_SERIES : view,
+ explorerViewToPanelType[view],
+ querySearchParameters,
);
},
- [
- handleSetConfig,
- handleExplorerTabChange,
- selectedView,
- currentQuery,
- updateAllQueriesOperators,
- updateQueriesData,
- setSelectedView,
- ],
+ [handleSetConfig, handleExplorerTabChange, setSelectedView],
);
- useShareBuilderUrl({
- defaultValue: defaultQuery,
- forceReset: shouldReset,
- });
-
- useEffect(() => {
- if (shouldReset) {
- setShouldReset(false);
- setDefaultQuery(
- updateAllQueriesOperators(
- initialQueriesMap.logs,
- PANEL_TYPES.LIST,
- DataSource.LOGS,
- ),
- );
- }
- }, [shouldReset, updateAllQueriesOperators]);
-
const handleFilterVisibilityChange = (): void => {
setLocalStorageApi(
LOCALSTORAGE.SHOW_LOGS_QUICK_FILTERS,
@@ -399,12 +312,12 @@ function LogsExplorer(): JSX.Element {
</div>
<div className="logs-explorer-views">
<LogsExplorerViewsContainer
- selectedView={selectedView}
listQueryKeyRef={listQueryKeyRef}
chartQueryKeyRef={chartQueryKeyRef}
setIsLoadingQueries={setIsLoadingQueries}
setWarning={setWarning}
showLiveLogs={showLiveLogs}
+ handleChangeSelectedView={handleChangeSelectedView}
/>
</div>
</div>
diff --git a/frontend/src/utils/explorerUtils.ts b/frontend/src/utils/explorerUtils.ts
index a897e28192..bd39715e30 100644
--- a/frontend/src/utils/explorerUtils.ts
+++ b/frontend/src/utils/explorerUtils.ts
@@ -15,6 +15,13 @@ export const panelTypeToExplorerView: Record<PANEL_TYPES, ExplorerViews> = {
[PANEL_TYPES.EMPTY_WIDGET]: ExplorerViews.LIST,
};
+export const explorerViewToPanelType = {
+ [ExplorerViews.LIST]: PANEL_TYPES.LIST,
+ [ExplorerViews.TIMESERIES]: PANEL_TYPES.TIME_SERIES,
+ [ExplorerViews.TRACE]: PANEL_TYPES.TRACE,
+ [ExplorerViews.TABLE]: PANEL_TYPES.TABLE,
+} as Record<ExplorerViews, PANEL_TYPES>;
+
/**
* Get the explorer view based on panel type from URL or saved view
* @param searchParams - URL search parameters