Skip to content
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

feat(query-builder): Add loading state and improved menu styles/positioning #72940

Merged
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
105 changes: 69 additions & 36 deletions static/app/components/searchQueryBuilder/combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import {
type MouseEventHandler,
type ReactNode,
useCallback,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import isPropValid from '@emotion/is-prop-valid';
import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import {type AriaComboBoxProps, useComboBox} from '@react-aria/combobox';
import type {AriaListBoxOptions} from '@react-aria/listbox';
Expand All @@ -30,12 +29,14 @@ import {
getHiddenOptions,
} from 'sentry/components/compactSelect/utils';
import {GrowingInput} from 'sentry/components/growingInput';
import {Overlay, PositionWrapper} from 'sentry/components/overlay';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import {Overlay} from 'sentry/components/overlay';
import type {Token, TokenResult} from 'sentry/components/searchSyntax/parser';
import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import mergeRefs from 'sentry/utils/mergeRefs';
import useOverlay from 'sentry/utils/useOverlay';
import usePrevious from 'sentry/utils/usePrevious';

type SearchQueryBuilderComboboxProps<T extends SelectOptionOrSectionWithKey<string>> = {
children: CollectionChildren<T>;
Expand Down Expand Up @@ -64,6 +65,7 @@ type SearchQueryBuilderComboboxProps<T extends SelectOptionOrSectionWithKey<stri
*/
displayTabbedMenu?: boolean;
filterValue?: string;
isLoading?: boolean;
maxOptions?: number;
/**
* Called when the user explicitly closes the combobox with the escape key.
Expand Down Expand Up @@ -118,25 +120,22 @@ function mergeSets<T>(...sets: Set<T>[]) {
function menuIsOpen({
state,
hiddenOptions,
items,
totalOptions,
displayTabbedMenu,
isLoading,
}: {
hiddenOptions: Set<SelectKey>;
items: SelectOptionOrSectionWithKey<string>[];
state: ComboBoxState<any>;
totalOptions: number;
displayTabbedMenu?: boolean;
isLoading?: boolean;
}) {
if (displayTabbedMenu) {
if (displayTabbedMenu || isLoading) {
return state.isOpen;
}

// When the tabbed menu is not being displayed, we only want to show the menu
// when there are options to select from
const totalOptions = items.reduce(
(acc, item) => acc + (itemIsSection(item) ? item.options.length : 1),
0
);

// When the tabbed menu is not being displayed and we aren't loading anything,
// only show when there is something to select from.
return state.isOpen && totalOptions > hiddenOptions.size;
}

Expand Down Expand Up @@ -271,7 +270,7 @@ function SectionedListBox<T extends SelectOptionOrSectionWithKey<string>>({
hiddenOptions={hiddenOptions}
keyDownHandler={() => true}
overlayIsOpen={isOpen}
size="md"
size="sm"
/>
</SectionedListBoxPane>
</SectionedOverlay>
Expand Down Expand Up @@ -300,10 +299,10 @@ function SearchQueryBuilderComboboxInner<T extends SelectOptionOrSectionWithKey<
shouldCloseOnInteractOutside,
onPaste,
displayTabbedMenu,
isLoading,
}: SearchQueryBuilderComboboxProps<T>,
ref: ForwardedRef<HTMLInputElement>
) {
const theme = useTheme();
const listBoxRef = useRef<HTMLUListElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -388,9 +387,23 @@ function SearchQueryBuilderComboboxInner<T extends SelectOptionOrSectionWithKey<
state
);

const isOpen = menuIsOpen({state, hiddenOptions, items, displayTabbedMenu});
const totalOptions = items.reduce(
(acc, item) => acc + (itemIsSection(item) ? item.options.length : 1),
0
);
const isOpen = menuIsOpen({
state,
hiddenOptions,
totalOptions,
displayTabbedMenu,
isLoading,
});

const {overlayProps, triggerProps} = useOverlay({
const {
overlayProps,
triggerProps,
update: updateOverlayPosition,
} = useOverlay({
type: 'listbox',
isOpen,
position: 'bottom-start',
Expand All @@ -406,8 +419,20 @@ function SearchQueryBuilderComboboxInner<T extends SelectOptionOrSectionWithKey<
}
state.close();
},
preventOverflowOptions: {boundary: document.body, altAxis: true},
});

const previousValues = usePrevious({isLoading, isOpen, inputValue});

useLayoutEffect(() => {
if (
(isOpen && previousValues?.inputValue !== inputValue) ||
previousValues?.isLoading !== isLoading
) {
updateOverlayPosition?.();
}
}, [inputValue, isLoading, isOpen, previousValues, updateOverlayPosition]);

const handleInputClick: MouseEventHandler<HTMLInputElement> = useCallback(
e => {
e.stopPropagation();
Expand All @@ -431,11 +456,7 @@ function SearchQueryBuilderComboboxInner<T extends SelectOptionOrSectionWithKey<
tabIndex={tabIndex}
onPaste={onPaste}
/>
<StyledPositionWrapper
{...overlayProps}
zIndex={theme.zIndex?.tooltip}
visible={isOpen}
>
<StyledPositionWrapper {...overlayProps} visible={isOpen}>
{displayTabbedMenu ? (
<SectionedListBox
popoverRef={popoverRef}
Expand All @@ -449,16 +470,22 @@ function SearchQueryBuilderComboboxInner<T extends SelectOptionOrSectionWithKey<
/>
) : (
<StyledOverlay ref={popoverRef}>
<ListBox
{...listBoxProps}
ref={listBoxRef}
listState={state}
hasSearch={!!filterValue}
hiddenOptions={hiddenOptions}
keyDownHandler={() => true}
overlayIsOpen={isOpen}
size="md"
/>
{isLoading && hiddenOptions.size >= totalOptions ? (
<LoadingWrapper>
<LoadingIndicator mini />
</LoadingWrapper>
) : (
<ListBox
{...listBoxProps}
ref={listBoxRef}
listState={state}
hasSearch={!!filterValue}
hiddenOptions={hiddenOptions}
keyDownHandler={() => true}
overlayIsOpen={isOpen}
size="sm"
/>
)}
</StyledOverlay>
)}
</StyledPositionWrapper>
Expand Down Expand Up @@ -499,16 +526,15 @@ const UnstyledInput = styled(GrowingInput)`
}
`;

const StyledPositionWrapper = styled(PositionWrapper, {
shouldForwardProp: prop => isPropValid(prop),
})<{visible?: boolean}>`
const StyledPositionWrapper = styled('div')<{visible?: boolean}>`
display: ${p => (p.visible ? 'block' : 'none')};
z-index: ${p => p.theme.zIndex.tooltip};
`;

const StyledOverlay = styled(Overlay)`
max-height: 400px;
min-width: 200px;
width: 300px;
width: 600px;
max-width: min-content;
overflow-y: auto;
`;
Expand Down Expand Up @@ -551,3 +577,10 @@ const SectionButton = styled(Button)`
font-weight: ${p => p.theme.fontWeightBold};
}
`;

const LoadingWrapper = styled('div')`
display: flex;
justify-content: center;
align-items: center;
height: 140px;
`;
22 changes: 21 additions & 1 deletion static/app/components/searchQueryBuilder/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ const FITLER_KEY_SECTIONS: FilterKeySection[] = [
{
key: 'custom_tag_name',
name: 'Custom_Tag_Name',
values: ['tag value one', 'tag value two', 'tag value three'],
},
],
},
Expand Down Expand Up @@ -919,6 +918,27 @@ describe('SearchQueryBuilder', function () {
within(groups[2]).getByRole('option', {name: '[email protected]'})
).toBeInTheDocument();
});

it('fetches tag values', async function () {
const mockGetTagValues = jest.fn().mockResolvedValue(['tag_value_one']);
render(
<SearchQueryBuilder
{...defaultProps}
initialQuery="custom_tag_name:"
getTagValues={mockGetTagValues}
/>
);

await userEvent.click(
screen.getByRole('button', {name: 'Edit value for filter: custom_tag_name'})
);
await screen.findByRole('option', {name: 'tag_value_one'});
await userEvent.click(screen.getByRole('option', {name: 'tag_value_one'}));

expect(
await screen.findByRole('row', {name: 'custom_tag_name:tag_value_one'})
).toBeInTheDocument();
});
});

describe('filter types', function () {
Expand Down
6 changes: 4 additions & 2 deletions static/app/components/searchQueryBuilder/valueCombobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ function useFilterSuggestions({
const canSelectMultipleValues = tokenSupportsMultipleValues(token, keys);

// TODO(malwilley): Display error states
const {data} = useQuery<string[]>({
const {data, isFetching} = useQuery<string[]>({
queryKey: ['search-query-builder', token.key, inputValue] as QueryKey,
queryFn: () => getTagValues(key, inputValue),
keepPreviousData: true,
Expand Down Expand Up @@ -452,6 +452,7 @@ function useFilterSuggestions({
return {
items,
suggestionSectionItems,
isFetching,
};
}

Expand Down Expand Up @@ -509,7 +510,7 @@ export function SearchQueryBuilderValueCombobox({
: [],
[canSelectMultipleValues, token]
);
const {items, suggestionSectionItems} = useFilterSuggestions({
const {items, suggestionSectionItems, isFetching} = useFilterSuggestions({
token,
inputValue,
selectedValues,
Expand Down Expand Up @@ -600,6 +601,7 @@ export function SearchQueryBuilderValueCombobox({
autoFocus
maxOptions={50}
openOnFocus
isLoading={isFetching}
// Ensure that the menu stays open when clicking on the selected items
shouldCloseOnInteractOutside={el => el !== ref.current}
>
Expand Down
Loading