@parca/profile 0.19.73 → 0.19.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/MatchersInput/index.d.ts.map +1 -1
  3. package/dist/MatchersInput/index.js +4 -2
  4. package/dist/ProfileExplorer/ProfileExplorerCompare.d.ts +1 -12
  5. package/dist/ProfileExplorer/ProfileExplorerCompare.d.ts.map +1 -1
  6. package/dist/ProfileExplorer/ProfileExplorerCompare.js +52 -11
  7. package/dist/ProfileExplorer/ProfileExplorerSingle.d.ts +1 -7
  8. package/dist/ProfileExplorer/ProfileExplorerSingle.d.ts.map +1 -1
  9. package/dist/ProfileExplorer/ProfileExplorerSingle.js +4 -2
  10. package/dist/ProfileExplorer/index.d.ts +1 -4
  11. package/dist/ProfileExplorer/index.d.ts.map +1 -1
  12. package/dist/ProfileExplorer/index.js +11 -225
  13. package/dist/ProfileMetricsGraph/index.d.ts +1 -1
  14. package/dist/ProfileMetricsGraph/index.d.ts.map +1 -1
  15. package/dist/ProfileMetricsGraph/index.js +16 -20
  16. package/dist/ProfileSelector/MetricsGraphSection.d.ts +3 -3
  17. package/dist/ProfileSelector/MetricsGraphSection.d.ts.map +1 -1
  18. package/dist/ProfileSelector/MetricsGraphSection.js +10 -6
  19. package/dist/ProfileSelector/index.d.ts +2 -7
  20. package/dist/ProfileSelector/index.d.ts.map +1 -1
  21. package/dist/ProfileSelector/index.js +40 -46
  22. package/dist/ProfileSelector/useAutoQuerySelector.d.ts.map +1 -1
  23. package/dist/ProfileSelector/useAutoQuerySelector.js +19 -4
  24. package/dist/ProfileTypeSelector/index.d.ts.map +1 -1
  25. package/dist/ProfileTypeSelector/index.js +1 -1
  26. package/dist/ProfileView/components/ViewSelector/index.d.ts.map +1 -1
  27. package/dist/ProfileView/components/ViewSelector/index.js +10 -4
  28. package/dist/ProfileView/hooks/useResetStateOnProfileTypeChange.d.ts.map +1 -1
  29. package/dist/ProfileView/hooks/useResetStateOnProfileTypeChange.js +4 -2
  30. package/dist/ProfileView/hooks/useVisualizationState.d.ts.map +1 -1
  31. package/dist/ProfileView/hooks/useVisualizationState.js +20 -13
  32. package/dist/Table/MoreDropdown.d.ts.map +1 -1
  33. package/dist/Table/MoreDropdown.js +7 -3
  34. package/dist/Table/TableContextMenu.d.ts.map +1 -1
  35. package/dist/Table/TableContextMenu.js +9 -5
  36. package/dist/hooks/useCompareModeMeta.d.ts +10 -0
  37. package/dist/hooks/useCompareModeMeta.d.ts.map +1 -0
  38. package/dist/hooks/useCompareModeMeta.js +113 -0
  39. package/dist/hooks/useQueryState.d.ts +32 -0
  40. package/dist/hooks/useQueryState.d.ts.map +1 -0
  41. package/dist/hooks/useQueryState.js +285 -0
  42. package/dist/hooks/useQueryState.test.d.ts +2 -0
  43. package/dist/hooks/useQueryState.test.d.ts.map +1 -0
  44. package/dist/hooks/useQueryState.test.js +910 -0
  45. package/dist/index.d.ts +4 -5
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +6 -3
  48. package/dist/useSumBy.d.ts +7 -0
  49. package/dist/useSumBy.d.ts.map +1 -1
  50. package/dist/useSumBy.js +31 -6
  51. package/package.json +6 -6
  52. package/src/MatchersInput/index.tsx +4 -2
  53. package/src/ProfileExplorer/ProfileExplorerCompare.tsx +64 -46
  54. package/src/ProfileExplorer/ProfileExplorerSingle.tsx +7 -19
  55. package/src/ProfileExplorer/index.tsx +11 -339
  56. package/src/ProfileMetricsGraph/index.tsx +16 -20
  57. package/src/ProfileSelector/MetricsGraphSection.tsx +14 -10
  58. package/src/ProfileSelector/index.tsx +65 -83
  59. package/src/ProfileSelector/useAutoQuerySelector.ts +23 -5
  60. package/src/ProfileTypeSelector/index.tsx +3 -1
  61. package/src/ProfileView/components/ViewSelector/index.tsx +9 -4
  62. package/src/ProfileView/hooks/useResetStateOnProfileTypeChange.ts +4 -2
  63. package/src/ProfileView/hooks/useVisualizationState.ts +25 -12
  64. package/src/Table/MoreDropdown.tsx +7 -3
  65. package/src/Table/TableContextMenu.tsx +9 -5
  66. package/src/hooks/useCompareModeMeta.ts +131 -0
  67. package/src/hooks/useQueryState.test.tsx +1202 -0
  68. package/src/hooks/useQueryState.ts +414 -0
  69. package/src/index.tsx +9 -11
  70. package/src/useSumBy.ts +62 -7
  71. package/src/ProfileExplorer/index.test.ts +0 -97
@@ -0,0 +1,414 @@
1
+ // Copyright 2022 The Parca Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+
14
+ import {useCallback, useEffect, useMemo, useState} from 'react';
15
+
16
+ import {DateTimeRange, useParcaContext, useURLState, useURLStateBatch} from '@parca/components';
17
+ import {Query} from '@parca/parser';
18
+
19
+ import {QuerySelection} from '../ProfileSelector';
20
+ import {ProfileSelection, ProfileSelectionFromParams, ProfileSource} from '../ProfileSource';
21
+ import {sumByToParam, useSumBy, useSumByFromParams} from '../useSumBy';
22
+
23
+ interface UseQueryStateOptions {
24
+ suffix?: '_a' | '_b'; // For comparison mode
25
+ defaultExpression?: string;
26
+ defaultTimeSelection?: string; // Should be in format like 'relative:hour|1' or 'absolute:...'
27
+ defaultFrom?: number;
28
+ defaultTo?: number;
29
+ comparing?: boolean; // If true, don't auto-select for delta profiles
30
+ }
31
+
32
+ interface UseQueryStateReturn {
33
+ // Current committed state (from URL)
34
+ querySelection: QuerySelection;
35
+
36
+ // Draft state (local changes not yet committed)
37
+ draftSelection: QuerySelection;
38
+
39
+ // Draft setters (update local state only)
40
+ setDraftExpression: (expression: string, commit?: boolean) => void;
41
+ setDraftTimeRange: (from: number, to: number, timeSelection: string) => void;
42
+ setDraftSumBy: (sumBy: string[] | undefined) => void;
43
+ setDraftProfileName: (profileName: string) => void;
44
+ setDraftMatchers: (matchers: string) => void;
45
+
46
+ // Commit function
47
+ commitDraft: (refreshedTimeRange?: {from: number; to: number; timeSelection: string}) => void;
48
+
49
+ // ProfileSelection state (separate from QuerySelection)
50
+ profileSelection: ProfileSelection | null;
51
+
52
+ // ProfileSource derived from ProfileSelection
53
+ profileSource: ProfileSource | null;
54
+
55
+ // ProfileSelection setter (auto-commits to URL)
56
+ setProfileSelection: (mergeFrom: bigint, mergeTo: bigint, query: Query) => void;
57
+
58
+ // Loading state for sumBy computation
59
+ sumByLoading: boolean;
60
+ }
61
+
62
+ export const useQueryState = (options: UseQueryStateOptions = {}): UseQueryStateReturn => {
63
+ const {queryServiceClient: queryClient} = useParcaContext();
64
+ const {
65
+ suffix = '',
66
+ defaultExpression = '',
67
+ defaultTimeSelection = 'relative:minute|15', // Default to 15 minutes relative
68
+ defaultFrom,
69
+ defaultTo,
70
+ comparing = false,
71
+ } = options;
72
+
73
+ const batchUpdates = useURLStateBatch();
74
+
75
+ // URL state hooks with appropriate suffixes
76
+ const [expression, setExpressionState] = useURLState<string>(`expression${suffix}`, {
77
+ defaultValue: defaultExpression,
78
+ });
79
+
80
+ const [from, setFromState] = useURLState<string>(`from${suffix}`, {
81
+ defaultValue: defaultFrom?.toString(),
82
+ });
83
+
84
+ const [to, setToState] = useURLState<string>(`to${suffix}`, {
85
+ defaultValue: defaultTo?.toString(),
86
+ });
87
+
88
+ const [timeSelection, setTimeSelectionState] = useURLState<string>(`time_selection${suffix}`, {
89
+ defaultValue: defaultTimeSelection,
90
+ });
91
+
92
+ const [sumByParam, setSumByParam] = useURLState<string>(`sum_by${suffix}`);
93
+
94
+ const [mergeFrom, setMergeFromState] = useURLState<string>(`merge_from${suffix}`);
95
+ const [mergeTo, setMergeToState] = useURLState<string>(`merge_to${suffix}`);
96
+
97
+ // ProfileSelection URL state hooks - reuses merge_from/merge_to but adds selection
98
+ const [selectionParam, setSelectionParam] = useURLState<string>(`selection${suffix}`);
99
+
100
+ // Parse sumBy from URL parameter format
101
+ const sumBy = useSumByFromParams(sumByParam);
102
+
103
+ // Draft state management
104
+ const [draftExpression, setDraftExpression] = useState<string>(expression ?? defaultExpression);
105
+ const [draftFrom, setDraftFrom] = useState<string>(from ?? defaultFrom?.toString() ?? '');
106
+ const [draftTo, setDraftTo] = useState<string>(to ?? defaultTo?.toString() ?? '');
107
+ const [draftTimeSelection, setDraftTimeSelection] = useState<string>(
108
+ timeSelection ?? defaultTimeSelection
109
+ );
110
+ const [draftSumBy, setDraftSumBy] = useState<string[] | undefined>(sumBy);
111
+
112
+ // Sync draft state with URL state when URL changes externally
113
+ useEffect(() => {
114
+ setDraftExpression(expression ?? defaultExpression);
115
+ }, [expression, defaultExpression]);
116
+
117
+ useEffect(() => {
118
+ setDraftFrom(from ?? defaultFrom?.toString() ?? '');
119
+ }, [from, defaultFrom]);
120
+
121
+ useEffect(() => {
122
+ setDraftTo(to ?? defaultTo?.toString() ?? '');
123
+ }, [to, defaultTo]);
124
+
125
+ useEffect(() => {
126
+ setDraftTimeSelection(timeSelection ?? defaultTimeSelection);
127
+ }, [timeSelection, defaultTimeSelection]);
128
+
129
+ useEffect(() => {
130
+ setDraftSumBy(sumBy);
131
+ }, [sumBy]);
132
+
133
+ // Parse the draft query to extract profile information
134
+ const draftQuery = useMemo(() => {
135
+ try {
136
+ return Query.parse(draftExpression ?? '');
137
+ } catch {
138
+ return Query.parse('');
139
+ }
140
+ }, [draftExpression]);
141
+
142
+ const draftProfileType = useMemo(() => draftQuery.profileType(), [draftQuery]);
143
+ const draftProfileName = useMemo(() => draftQuery.profileName(), [draftQuery]);
144
+
145
+ // Compute draft time range for label fetching
146
+ const draftTimeRange = useMemo(() => {
147
+ return DateTimeRange.fromRangeKey(
148
+ draftTimeSelection ?? defaultTimeSelection,
149
+ draftFrom !== '' ? parseInt(draftFrom) : defaultFrom,
150
+ draftTo !== '' ? parseInt(draftTo) : defaultTo
151
+ );
152
+ }, [draftTimeSelection, draftFrom, draftTo, defaultTimeSelection, defaultFrom, defaultTo]);
153
+
154
+ // Use combined sumBy hook for fetching labels and computing defaults (based on committed state)
155
+ const {sumBy: computedSumByFromURL, isLoading: sumBySelectionLoading} = useSumBy(
156
+ queryClient,
157
+ draftProfileType,
158
+ draftTimeRange,
159
+ sumBy
160
+ );
161
+
162
+ // Construct the QuerySelection object (committed state from URL)
163
+ const querySelection: QuerySelection = useMemo(() => {
164
+ const range = DateTimeRange.fromRangeKey(
165
+ timeSelection ?? defaultTimeSelection,
166
+ from !== undefined && from !== '' ? parseInt(from) : defaultFrom,
167
+ to !== undefined && to !== '' ? parseInt(to) : defaultTo
168
+ );
169
+
170
+ return {
171
+ expression: expression ?? defaultExpression,
172
+ from: range.getFromMs(),
173
+ to: range.getToMs(),
174
+ timeSelection: range.getRangeKey(),
175
+ sumBy: computedSumByFromURL,
176
+ ...(mergeFrom !== undefined && mergeFrom !== '' && mergeTo !== undefined && mergeTo !== ''
177
+ ? {mergeFrom, mergeTo}
178
+ : {}),
179
+ };
180
+ }, [
181
+ expression,
182
+ from,
183
+ to,
184
+ timeSelection,
185
+ computedSumByFromURL,
186
+ mergeFrom,
187
+ mergeTo,
188
+ defaultExpression,
189
+ defaultTimeSelection,
190
+ defaultFrom,
191
+ defaultTo,
192
+ ]);
193
+
194
+ // Construct the draft QuerySelection object (local draft state)
195
+ const draftSelection: QuerySelection = useMemo(() => {
196
+ const isDelta = draftProfileType.delta;
197
+ const draftMergeFrom = isDelta
198
+ ? (BigInt(draftTimeRange.getFromMs()) * 1_000_000n).toString()
199
+ : undefined;
200
+ const draftMergeTo = isDelta
201
+ ? (BigInt(draftTimeRange.getToMs()) * 1_000_000n).toString()
202
+ : undefined;
203
+
204
+ return {
205
+ expression: draftExpression ?? defaultExpression,
206
+ from: draftTimeRange.getFromMs(),
207
+ to: draftTimeRange.getToMs(),
208
+ timeSelection: draftTimeRange.getRangeKey(),
209
+ sumBy: draftSumBy ?? computedSumByFromURL, // Use draft if set, otherwise fallback to computed
210
+ ...(draftMergeFrom !== undefined &&
211
+ draftMergeFrom !== '' &&
212
+ draftMergeTo !== undefined &&
213
+ draftMergeTo !== ''
214
+ ? {mergeFrom: draftMergeFrom, mergeTo: draftMergeTo}
215
+ : {}),
216
+ };
217
+ }, [
218
+ draftExpression,
219
+ draftTimeRange,
220
+ draftSumBy,
221
+ computedSumByFromURL,
222
+ draftProfileType.delta,
223
+ defaultExpression,
224
+ ]);
225
+
226
+ // Compute ProfileSelection from URL params
227
+ const profileSelection = useMemo<ProfileSelection | null>(() => {
228
+ return ProfileSelectionFromParams(mergeFrom, mergeTo, selectionParam);
229
+ }, [mergeFrom, mergeTo, selectionParam]);
230
+
231
+ // Compute ProfileSource from ProfileSelection
232
+ const profileSource = useMemo<ProfileSource | null>(() => {
233
+ if (profileSelection === null) return null;
234
+ return profileSelection.ProfileSource();
235
+ }, [profileSelection]);
236
+
237
+ // Commit draft changes to URL
238
+ // Optional refreshedTimeRange parameter allows re-evaluating relative time ranges (e.g., "last 15 minutes")
239
+ // to the current moment when the Search button is clicked
240
+ // Optional expression parameter allows updating the expression before committing
241
+ const commitDraft = useCallback(
242
+ (
243
+ refreshedTimeRange?: {from: number; to: number; timeSelection: string},
244
+ expression?: string
245
+ ) => {
246
+ batchUpdates(() => {
247
+ // Use provided expression or current draft expression
248
+ const finalExpression = expression ?? draftExpression;
249
+
250
+ // Update draft state with new expression if provided
251
+ if (expression !== undefined) {
252
+ setDraftExpression(expression);
253
+ }
254
+
255
+ // Calculate the actual from/to values from draftSelection if not provided
256
+ const calculatedFrom = draftSelection.from.toString();
257
+ const calculatedTo = draftSelection.to.toString();
258
+
259
+ const finalFrom =
260
+ refreshedTimeRange?.from?.toString() ?? (draftFrom !== '' ? draftFrom : calculatedFrom);
261
+ const finalTo =
262
+ refreshedTimeRange?.to?.toString() ?? (draftTo !== '' ? draftTo : calculatedTo);
263
+ const finalTimeSelection = refreshedTimeRange?.timeSelection ?? draftTimeSelection;
264
+
265
+ // Update draft state with refreshed time range if provided
266
+ if (refreshedTimeRange?.from !== undefined) {
267
+ setDraftFrom(finalFrom);
268
+ }
269
+ if (refreshedTimeRange?.to !== undefined) {
270
+ setDraftTo(finalTo);
271
+ }
272
+ if (refreshedTimeRange?.timeSelection !== undefined) {
273
+ setDraftTimeSelection(finalTimeSelection);
274
+ }
275
+
276
+ setExpressionState(finalExpression);
277
+ setFromState(finalFrom);
278
+ setToState(finalTo);
279
+ setTimeSelectionState(finalTimeSelection);
280
+ setSumByParam(sumByToParam(draftSumBy));
281
+
282
+ // Auto-calculate merge parameters for delta profiles
283
+ // Parse the final expression to check if it's a delta profile
284
+ const finalQuery = Query.parse(finalExpression);
285
+ const isDelta = finalQuery.profileType().delta;
286
+
287
+ if (isDelta && finalFrom !== '' && finalTo !== '') {
288
+ const fromMs = parseInt(finalFrom);
289
+ const toMs = parseInt(finalTo);
290
+ setMergeFromState((BigInt(fromMs) * 1_000_000n).toString());
291
+ setMergeToState((BigInt(toMs) * 1_000_000n).toString());
292
+
293
+ // Auto-select the time range for delta profiles (but not in compare mode)
294
+ // This applies both on initial load AND when Search is clicked
295
+ // The selection will use the final expression and the updated time range
296
+ if (!comparing) {
297
+ setSelectionParam(finalExpression);
298
+ } else {
299
+ setSelectionParam(undefined);
300
+ }
301
+ } else {
302
+ setMergeFromState(undefined);
303
+ setMergeToState(undefined);
304
+ // Clear ProfileSelection for non-delta profiles
305
+ setSelectionParam(undefined);
306
+ }
307
+ });
308
+ },
309
+ [
310
+ batchUpdates,
311
+ draftExpression,
312
+ draftFrom,
313
+ draftTo,
314
+ draftTimeSelection,
315
+ draftSumBy,
316
+ draftSelection.from,
317
+ draftSelection.to,
318
+ comparing,
319
+ setExpressionState,
320
+ setFromState,
321
+ setToState,
322
+ setTimeSelectionState,
323
+ setSumByParam,
324
+ setMergeFromState,
325
+ setMergeToState,
326
+ setSelectionParam,
327
+ ]
328
+ );
329
+
330
+ // Draft setters (update local state only, or commit directly if specified)
331
+ const setDraftExpressionCallback = useCallback(
332
+ (newExpression: string, commit = false) => {
333
+ if (commit) {
334
+ // Commit with the new expression, which will also update merge params and selection
335
+ commitDraft(undefined, newExpression);
336
+ } else {
337
+ // Only update draft state
338
+ setDraftExpression(newExpression);
339
+ }
340
+ },
341
+ [commitDraft]
342
+ );
343
+
344
+ const setDraftTimeRange = useCallback(
345
+ (newFrom: number, newTo: number, newTimeSelection: string) => {
346
+ setDraftFrom(newFrom.toString());
347
+ setDraftTo(newTo.toString());
348
+ setDraftTimeSelection(newTimeSelection);
349
+ },
350
+ []
351
+ );
352
+
353
+ const setDraftSumByCallback = useCallback((newSumBy: string[] | undefined) => {
354
+ setDraftSumBy(newSumBy);
355
+ }, []);
356
+
357
+ const setDraftProfileName = useCallback(
358
+ (newProfileName: string) => {
359
+ if (newProfileName === '') return;
360
+
361
+ const [newQuery, changed] = draftQuery.setProfileName(newProfileName);
362
+ if (changed) {
363
+ setDraftExpression(newQuery.toString());
364
+ }
365
+ },
366
+ [draftQuery]
367
+ );
368
+
369
+ const setDraftMatchers = useCallback(
370
+ (matchers: string) => {
371
+ const newExpression = `${draftProfileName}{${matchers}}`;
372
+ setDraftExpression(newExpression);
373
+ },
374
+ [draftProfileName]
375
+ );
376
+
377
+ // Set ProfileSelection (auto-commits to URL immediately)
378
+ const setProfileSelection = useCallback(
379
+ (mergeFrom: bigint, mergeTo: bigint, query: Query) => {
380
+ batchUpdates(() => {
381
+ setSelectionParam(query.toString());
382
+ setMergeFromState(mergeFrom.toString());
383
+ setMergeToState(mergeTo.toString());
384
+ });
385
+ },
386
+ [batchUpdates, setSelectionParam, setMergeFromState, setMergeToState]
387
+ );
388
+
389
+ return {
390
+ // Current committed state
391
+ querySelection,
392
+
393
+ // Draft state
394
+ draftSelection,
395
+
396
+ // Draft setters
397
+ setDraftExpression: setDraftExpressionCallback,
398
+ setDraftTimeRange,
399
+ setDraftSumBy: setDraftSumByCallback,
400
+ setDraftProfileName,
401
+ setDraftMatchers,
402
+
403
+ // Commit function
404
+ commitDraft,
405
+
406
+ // ProfileSelection state
407
+ profileSelection,
408
+ profileSource,
409
+ setProfileSelection,
410
+
411
+ // Loading state
412
+ sumByLoading: sumBySelectionLoading,
413
+ };
414
+ };
package/src/index.tsx CHANGED
@@ -11,8 +11,10 @@
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
13
 
14
+ import type {ParamPreferences} from '@parca/components';
15
+
14
16
  import {useLabelNames} from './MatchersInput';
15
- import ProfileExplorer, {getExpressionAsAString} from './ProfileExplorer';
17
+ import ProfileExplorer from './ProfileExplorer';
16
18
  import ProfileTypeSelector from './ProfileTypeSelector';
17
19
  import SelectWithRefresh from './SelectWithRefresh';
18
20
  import CustomSelect from './SimpleMatchers/Select';
@@ -34,15 +36,11 @@ export * from './useSumBy';
34
36
  export {default as ProfileFilters} from './ProfileView/components/ProfileFilters';
35
37
  export {useProfileFiltersUrlState} from './ProfileView/components/ProfileFilters/useProfileFiltersUrlState';
36
38
 
37
- export const DEFAULT_PROFILE_EXPLORER_PARAM_VALUES = {
38
- dashboard_items: 'flamegraph',
39
+ export const DEFAULT_PROFILE_EXPLORER_PARAM_VALUES: ParamPreferences = {
40
+ dashboard_items: {
41
+ defaultValue: 'flamegraph',
42
+ splitOnCommas: true, // This param should split on commas for array values
43
+ },
39
44
  };
40
45
 
41
- export {
42
- ProfileExplorer,
43
- ProfileTypeSelector,
44
- getExpressionAsAString,
45
- CustomSelect,
46
- SelectWithRefresh,
47
- useLabelNames,
48
- };
46
+ export {ProfileExplorer, ProfileTypeSelector, CustomSelect, SelectWithRefresh, useLabelNames};
package/src/useSumBy.ts CHANGED
@@ -11,10 +11,14 @@
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
13
 
14
- import {useCallback, useEffect, useMemo, useState} from 'react';
14
+ import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
15
15
 
16
+ import {QueryServiceClient} from '@parca/client';
17
+ import {DateTimeRange} from '@parca/components';
16
18
  import {ProfileType} from '@parca/parser';
17
19
 
20
+ import {useLabelNames} from './MatchersInput/index';
21
+
18
22
  export const DEFAULT_EMPTY_SUM_BY: string[] = [];
19
23
 
20
24
  const getDefaultSumBy = (
@@ -92,15 +96,30 @@ export const useSumBySelection = (
92
96
 
93
97
  const {defaultSumBy} = useDefaultSumBy(profileType, labelNamesLoading, labels);
94
98
 
95
- let sumBy =
96
- userSelectedSumBy[profileType?.toString() ?? ''] ?? defaultSumBy ?? DEFAULT_EMPTY_SUM_BY;
99
+ // Store the last valid sumBy value to return during loading
100
+ const lastValidSumByRef = useRef<string[]>(DEFAULT_EMPTY_SUM_BY);
97
101
 
98
- if (profileType?.delta !== true) {
99
- sumBy = DEFAULT_EMPTY_SUM_BY;
100
- }
102
+ const sumBy = useMemo(() => {
103
+ // If loading, return the last valid value to prevent input from blanking
104
+ if (labelNamesLoading && lastValidSumByRef.current !== DEFAULT_EMPTY_SUM_BY) {
105
+ return lastValidSumByRef.current;
106
+ }
107
+
108
+ let result =
109
+ userSelectedSumBy[profileType?.toString() ?? ''] ?? defaultSumBy ?? DEFAULT_EMPTY_SUM_BY;
110
+
111
+ if (profileType?.delta !== true) {
112
+ result = DEFAULT_EMPTY_SUM_BY;
113
+ }
114
+
115
+ // Store the computed value for next loading state
116
+ lastValidSumByRef.current = result;
117
+
118
+ return result;
119
+ }, [userSelectedSumBy, profileType, defaultSumBy, labelNamesLoading]);
101
120
 
102
121
  return [
103
- labelNamesLoading ? undefined : sumBy,
122
+ sumBy,
104
123
  setSumBy,
105
124
  {
106
125
  isLoading: labelNamesLoading,
@@ -162,3 +181,39 @@ export const sumByToParam = (sumBy: string[] | undefined): string | string[] | u
162
181
 
163
182
  return sumBy;
164
183
  };
184
+
185
+ // Combined hook that handles all sumBy logic: fetching labels, computing defaults, and managing selection
186
+ export const useSumBy = (
187
+ queryClient: QueryServiceClient,
188
+ profileType: ProfileType | undefined,
189
+ timeRange: DateTimeRange,
190
+ defaultValue?: string[]
191
+ ): {
192
+ sumBy: string[] | undefined;
193
+ setSumBy: (sumBy: string[]) => void;
194
+ isLoading: boolean;
195
+ } => {
196
+ const {loading: labelNamesLoading, result} = useLabelNames(
197
+ queryClient,
198
+ profileType?.toString() ?? '',
199
+ timeRange.getFromMs(),
200
+ timeRange.getToMs()
201
+ );
202
+
203
+ const labels = useMemo(() => {
204
+ return result.response?.labelNames === undefined ? [] : result.response.labelNames;
205
+ }, [result]);
206
+
207
+ const [sumBySelection, setSumByInternal, {isLoading}] = useSumBySelection(
208
+ profileType,
209
+ labelNamesLoading,
210
+ labels,
211
+ {defaultValue}
212
+ );
213
+
214
+ return {
215
+ sumBy: sumBySelection,
216
+ setSumBy: setSumByInternal,
217
+ isLoading,
218
+ };
219
+ };
@@ -1,97 +0,0 @@
1
- // Copyright 2022 The Parca Authors
2
- // Licensed under the Apache License, Version 2.0 (the "License");
3
- // you may not use this file except in compliance with the License.
4
- // You may obtain a copy of the License at
5
- //
6
- // http://www.apache.org/licenses/LICENSE-2.0
7
- //
8
- // Unless required by applicable law or agreed to in writing, software
9
- // distributed under the License is distributed on an "AS IS" BASIS,
10
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- // See the License for the specific language governing permissions and
12
- // limitations under the License.
13
-
14
- import {describe, expect, it} from 'vitest';
15
-
16
- import {filterEmptyParams} from './index';
17
-
18
- describe('filterEmptyParams', () => {
19
- it('should return an array with 2 elements when given object with 2 valid and multiple invalid values', () => {
20
- const input = {
21
- validString: 'hello',
22
- validArray: ['item1', 'item2'],
23
- emptyString: '',
24
- undefinedValue: undefined,
25
- emptyArray: [],
26
- anotherEmptyString: '',
27
- };
28
-
29
- const result = filterEmptyParams(input);
30
- const resultEntries = Object.entries(result);
31
-
32
- expect(resultEntries).toHaveLength(2);
33
- expect(result).toEqual({
34
- validString: 'hello',
35
- validArray: ['item1', 'item2'],
36
- });
37
- });
38
-
39
- it('should filter out empty strings', () => {
40
- const input = {
41
- valid: 'test',
42
- empty: '',
43
- };
44
-
45
- const result = filterEmptyParams(input);
46
- expect(result).toEqual({valid: 'test'});
47
- });
48
-
49
- it('should filter out undefined values', () => {
50
- const input = {
51
- valid: 'test',
52
- notDefined: undefined,
53
- };
54
-
55
- const result = filterEmptyParams(input);
56
- expect(result).toEqual({valid: 'test'});
57
- });
58
-
59
- it('should filter out empty arrays', () => {
60
- const input = {
61
- valid: 'test',
62
- emptyArray: [],
63
- nonEmptyArray: ['item'],
64
- };
65
-
66
- const result = filterEmptyParams(input);
67
- expect(result).toEqual({
68
- valid: 'test',
69
- nonEmptyArray: ['item'],
70
- });
71
- });
72
-
73
- it('should keep all valid values including numbers, booleans, and objects', () => {
74
- const input = {
75
- string: 'test',
76
- number: 0,
77
- boolean: false,
78
- object: {key: 'value'},
79
- array: ['item'],
80
- };
81
-
82
- const result = filterEmptyParams(input);
83
- expect(result).toEqual(input);
84
- });
85
-
86
- it('should return empty object when all values are invalid', () => {
87
- const input = {
88
- empty1: '',
89
- empty2: '',
90
- undefined1: undefined,
91
- emptyArray: [],
92
- };
93
-
94
- const result = filterEmptyParams(input);
95
- expect(result).toEqual({});
96
- });
97
- });