Skip to content

feat: add search history for search page #749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 17, 2025
Merged
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
5 changes: 5 additions & 0 deletions .changeset/sweet-kiwis-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hyperdx/app": patch
---

Add search history
66 changes: 65 additions & 1 deletion packages/app/src/AutocompleteInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Fuse from 'fuse.js';
import { OverlayTrigger } from 'react-bootstrap';
import { TextInput } from '@mantine/core';
import { TextInput, UnstyledButton } from '@mantine/core';

import { useQueryHistory } from '@/utils';

import InputLanguageSwitch from './components/InputLanguageSwitch';
import { useDebounce } from './utils';
Expand All @@ -22,6 +24,7 @@ export default function AutocompleteInput({
language,
showHotkey,
onSubmit,
queryHistoryType,
}: {
inputRef: React.RefObject<HTMLInputElement>;
value: string;
Expand All @@ -38,21 +41,46 @@ export default function AutocompleteInput({
onLanguageChange?: (language: 'sql' | 'lucene') => void;
language?: 'sql' | 'lucene';
showHotkey?: boolean;
queryHistoryType?: string;
}) {
const suggestionsLimit = 10;

const [isSearchInputFocused, setIsSearchInputFocused] = useState(false);
const [isInputDropdownOpen, setIsInputDropdownOpen] = useState(false);
const [showSearchHistory, setShowSearchHistory] = useState(false);

const [selectedAutocompleteIndex, setSelectedAutocompleteIndex] =
useState(-1);

const [selectedQueryHistoryIndex, setSelectedQueryHistoryIndex] =
useState(-1);
// query search history
const [queryHistory, setQueryHistory] = useQueryHistory(queryHistoryType);
const queryHistoryList = useMemo(() => {
if (!queryHistoryType || !queryHistory) return [];
return queryHistory.map(q => {
return {
value: q,
label: q,
};
});
}, [queryHistory]);

useEffect(() => {
if (isSearchInputFocused) {
setIsInputDropdownOpen(true);
}
}, [isSearchInputFocused]);

useEffect(() => {
// only show search history when: 1.no input, 2.has search type, 3.has history list
if (value.length === 0 && queryHistoryList.length > 0 && queryHistoryType) {
setShowSearchHistory(true);
} else {
setShowSearchHistory(false);
}
}, [value, queryHistoryType, queryHistoryList]);

const fuse = useMemo(
() =>
new Fuse(autocompleteOptions ?? [], {
Expand All @@ -74,6 +102,14 @@ export default function AutocompleteInput({
return fuse.search(lastToken).map(result => result.item);
}, [debouncedValue, fuse, autocompleteOptions, showSuggestionsOnEmpty]);

const onSelectSearchHistory = (query: string) => {
setSelectedQueryHistoryIndex(-1);
onChange(query); // update inputText bar
setQueryHistory(query); // update history order
setIsInputDropdownOpen(false); // close dropdown since we execute search
onSubmit?.(); // search
};

const onAcceptSuggestion = (suggestion: string) => {
setSelectedAutocompleteIndex(-1);

Expand Down Expand Up @@ -154,6 +190,29 @@ export default function AutocompleteInput({
{belowSuggestions}
</div>
)}
<div>
{showSearchHistory && (
<div className="border-top border-dark fs-8 py-2">
<div className="text-muted fs-8 fw-bold me-1 px-3">
Search History:
</div>
{queryHistoryList.map(({ value, label }, i) => {
return (
<UnstyledButton
className={`d-block w-100 text-start text-muted fw-normal px-3 py-2 fs-8 ${
selectedQueryHistoryIndex === i ? 'bg-hdx-dark' : ''
}`}
key={value}
onMouseOver={() => setSelectedQueryHistoryIndex(i)}
onClick={() => onSelectSearchHistory(value)}
>
<span className="me-1 text-truncate">{label}</span>
</UnstyledButton>
);
})}
</div>
)}
</div>
</div>
)}
popperConfig={{
Expand All @@ -179,10 +238,12 @@ export default function AutocompleteInput({
onChange={e => onChange(e.target.value)}
onFocus={() => {
setSelectedAutocompleteIndex(-1);
setSelectedQueryHistoryIndex(-1);
setIsSearchInputFocused(true);
}}
onBlur={() => {
setSelectedAutocompleteIndex(-1);
setSelectedQueryHistoryIndex(-1);
setIsSearchInputFocused(false);
}}
onKeyDown={e => {
Expand Down Expand Up @@ -213,6 +274,9 @@ export default function AutocompleteInput({
suggestedProperties[selectedAutocompleteIndex].value,
);
} else {
if (queryHistoryType) {
setQueryHistory(value);
}
onSubmit?.();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a heads up. In a separate PR, I will add icons for these as part of the larger story for adding icons next to items in the dropdown.

image

Expand Down
5 changes: 4 additions & 1 deletion packages/app/src/DBSearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ import {
useSources,
} from '@/source';
import { parseTimeQuery, useNewTimeQuery } from '@/timeQuery';
import { usePrevious } from '@/utils';
import { QUERY_LOCAL_STORAGE, usePrevious } from '@/utils';

import { SQLPreview } from './components/ChartSQLPreview';
import { useSqlSuggestions } from './hooks/useSqlSuggestions';
Expand Down Expand Up @@ -1146,6 +1146,7 @@ function DBSearchPage() {
language="sql"
onSubmit={onSubmit}
label="WHERE"
queryHistoryType={QUERY_LOCAL_STORAGE.SEARCH_SQL}
enableHotkey
/>
}
Expand All @@ -1159,8 +1160,10 @@ function DBSearchPage() {
shouldDirty: true,
})
}
onSubmit={onSubmit}
language="lucene"
placeholder="Search your events w/ Lucene ex. column:foo"
queryHistoryType={QUERY_LOCAL_STORAGE.SEARCH_LUCENE}
enableHotkey
/>
}
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/SearchInputV2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export default function SearchInputV2({
enableHotkey,
onSubmit,
additionalSuggestions,
queryHistoryType,
...props
}: {
tableConnections?: TableConnection | TableConnection[];
Expand All @@ -44,6 +45,7 @@ export default function SearchInputV2({
enableHotkey?: boolean;
onSubmit?: () => void;
additionalSuggestions?: string[];
queryHistoryType?: string;
} & UseControllerProps<any>) {
const {
field: { onChange, value },
Expand Down Expand Up @@ -91,6 +93,7 @@ export default function SearchInputV2({
showHotkey={enableHotkey}
onLanguageChange={onLanguageChange}
onSubmit={onSubmit}
queryHistoryType={queryHistoryType}
aboveSuggestions={
<>
<div className="text-muted fs-8 fw-bold me-1">Searching for:</div>
Expand Down
65 changes: 65 additions & 0 deletions packages/app/src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
formatDate,
formatNumber,
getMetricTableName,
useQueryHistory,
} from '../utils';

describe('utils', () => {
Expand Down Expand Up @@ -471,3 +472,67 @@ describe('useLocalStorage', () => {
expect(localStorageMock.getItem).not.toHaveBeenCalled();
});
});

describe('useQueryHistory', () => {
const mockGetItem = jest.fn();
const mockSetItem = jest.fn();
const mockRemoveItem = jest.fn();
const originalLocalStorage = window.localStorage;

beforeEach(() => {
mockGetItem.mockClear();
mockSetItem.mockClear();
mockRemoveItem.mockClear();
mockGetItem.mockReturnValue('["service = test3","service = test1"]');
Object.defineProperty(window, 'localStorage', {
value: {
getItem: (...args: string[]) => mockGetItem(...args),
setItem: (...args: string[]) => mockSetItem(...args),
removeItem: (...args: string[]) => mockRemoveItem(...args),
},
});
});

afterEach(() => {
jest.restoreAllMocks();
Object.defineProperty(window, 'localStorage', {
value: originalLocalStorage,
configurable: true,
});
});

it('adds new query', () => {
const { result } = renderHook(() => useQueryHistory('searchSQL'));
const setQueryHistory = result.current[1];
act(() => {
setQueryHistory('service = test2');
});

expect(mockSetItem).toHaveBeenCalledWith(
'QuerySearchHistory.searchSQL',
'["service = test2","service = test3","service = test1"]',
);
});

it('does not add duplicate query, but change the order to front', () => {
const { result } = renderHook(() => useQueryHistory('searchSQL'));
const setQueryHistory = result.current[1];
act(() => {
setQueryHistory('service = test1');
});

expect(mockSetItem).toHaveBeenCalledWith(
'QuerySearchHistory.searchSQL',
'["service = test1","service = test3"]',
);
});

it('does not add empty query', () => {
const { result } = renderHook(() => useQueryHistory('searchSQL'));
const setQueryHistory = result.current[1];
act(() => {
setQueryHistory(' '); // empty after trim
});
expect(mockSetItem).not.toBeCalled();
});
});
Loading