12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232 |
- import * as React from 'react';
- import TextareaAutosize from 'react-autosize-textarea';
- import {withRouter, WithRouterProps} from 'react-router';
- import isPropValid from '@emotion/is-prop-valid';
- import styled from '@emotion/styled';
- import * as Sentry from '@sentry/react';
- import debounce from 'lodash/debounce';
- import {addErrorMessage} from 'app/actionCreators/indicator';
- import {fetchRecentSearches, saveRecentSearch} from 'app/actionCreators/savedSearches';
- import {Client} from 'app/api';
- import ButtonBar from 'app/components/buttonBar';
- import DropdownLink from 'app/components/dropdownLink';
- import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
- import {ParseResult, parseSearch} from 'app/components/searchSyntax/parser';
- import HighlightQuery from 'app/components/searchSyntax/renderer';
- import {
- DEFAULT_DEBOUNCE_DURATION,
- MAX_AUTOCOMPLETE_RELEASES,
- NEGATION_OPERATOR,
- } from 'app/constants';
- import {IconClose, IconEllipsis, IconSearch} from 'app/icons';
- import {t} from 'app/locale';
- import MemberListStore from 'app/stores/memberListStore';
- import space from 'app/styles/space';
- import {LightWeightOrganization, SavedSearchType, Tag, User} from 'app/types';
- import {defined} from 'app/utils';
- import {trackAnalyticsEvent} from 'app/utils/analytics';
- import {callIfFunction} from 'app/utils/callIfFunction';
- import withApi from 'app/utils/withApi';
- import withOrganization from 'app/utils/withOrganization';
- import {ActionButton} from './actions';
- import SearchDropdown from './searchDropdown';
- import {ItemType, SearchGroup, SearchItem} from './types';
- import {
- addSpace,
- createSearchGroups,
- filterSearchGroupsByIndex,
- getLastTermIndex,
- getQueryTerms,
- removeSpace,
- } from './utils';
- const DROPDOWN_BLUR_DURATION = 200;
- /**
- * The max width in pixels of the search bar at which the buttons will
- * have overflowed into the dropdown.
- */
- const ACTION_OVERFLOW_WIDTH = 400;
- /**
- * Actions are moved to the overflow dropdown after each pixel step is reached.
- */
- const ACTION_OVERFLOW_STEPS = 75;
- /**
- * Is the SearchItem a default item
- */
- const isDefaultDropdownItem = (item: SearchItem) => item?.type === 'default';
- const makeQueryState = (query: string) => ({
- query,
- parsedQuery: parseSearch(query),
- });
- type ActionProps = {
- api: Client;
- /**
- * Render the actions as a menu item
- */
- menuItemVariant?: boolean;
- /**
- * The current query
- */
- query: string;
- /**
- * The organization
- */
- organization: LightWeightOrganization;
- /**
- * The saved search type passed to the search bar
- */
- savedSearchType?: SavedSearchType;
- };
- type ActionBarItem = {
- /**
- * Name of the action
- */
- key: string;
- /**
- * The action component to render
- */
- Action: React.ComponentType<ActionProps>;
- };
- type Props = WithRouterProps & {
- api: Client;
- organization: LightWeightOrganization;
- dropdownClassName?: string;
- className?: string;
- defaultQuery?: string;
- query?: string | null;
- /**
- * Additional components to render as actions on the right of the search bar
- */
- actionBarItems?: ActionBarItem[];
- /**
- * Prepare query value before filtering dropdown items
- */
- prepareQuery?: (query: string) => string;
- /**
- * Search items to display when there's no tag key. Is a tuple of search
- * items and recent search items
- */
- defaultSearchItems?: [SearchItem[], SearchItem[]];
- /**
- * Disabled control (e.g. read-only)
- */
- disabled?: boolean;
- /**
- * Input placeholder
- */
- placeholder?: string;
- /**
- * Allows additional content to be played before the search bar and icon
- */
- inlineLabel?: React.ReactNode;
- /**
- * Map of tags
- */
- supportedTags?: {[key: string]: Tag};
- /**
- * Maximum number of search items to display or a falsey value for no
- * maximum
- */
- maxSearchItems?: number;
- /**
- * List user's recent searches
- */
- hasRecentSearches?: boolean;
- /**
- * Wrap the input with a form. Useful if search bar is used within a parent
- * form
- */
- useFormWrapper?: boolean;
- /**
- * If this is defined, attempt to save search term scoped to the user and
- * the current org
- */
- savedSearchType?: SavedSearchType;
- /**
- * Get a list of tag values for the passed tag
- */
- onGetTagValues?: (tag: Tag, query: string, params: object) => Promise<string[]>;
- /**
- * Get a list of recent searches for the current query
- */
- onGetRecentSearches?: (query: string) => Promise<SearchItem[]>;
- /**
- * Called when the user makes a search
- */
- onSearch?: (query: string) => void;
- /**
- * Called when the search input changes
- */
- onChange?: (value: string, e: React.ChangeEvent) => void;
- /**
- * Called when the search is blurred
- */
- onBlur?: (value: string) => void;
- /**
- * Called on key down
- */
- onKeyDown?: (evt: React.KeyboardEvent<HTMLTextAreaElement>) => void;
- /**
- * Called when a recent search is saved
- */
- onSavedRecentSearch?: (query: string) => void;
- /**
- * If true, excludes the environment tag from the autocompletion list. This
- * is because we don't want to treat environment as a tag in some places such
- * as the stream view where it is a top level concept
- */
- excludeEnvironment?: boolean;
- /**
- * Used to enforce length on the query
- */
- maxQueryLength?: number;
- /**
- * While the data is unused, this list of members can be updated to
- * trigger re-renders.
- */
- members?: User[];
- };
- type State = {
- /**
- * The current search query in the input
- */
- query: string;
- /**
- * The query parsed into an AST. If the query fails to parse this will be
- * null.
- */
- parsedQuery: ParseResult | null;
- /**
- * The query in the input since we last updated our autocomplete list.
- */
- previousQuery?: string;
- /**
- * Indicates that we have a query that we've already determined not to have
- * any values. This is used to stop the autocompleter from querying if we
- * know we will find nothing.
- */
- noValueQuery?: string;
- /**
- * The current search term (or 'key') that that we will be showing
- * autocompletion for.
- */
- searchTerm: string;
- searchGroups: SearchGroup[];
- flatSearchItems: SearchItem[];
- /**
- * Index of the focused search item
- */
- activeSearchItem: number;
- tags: Record<string, string>;
- dropdownVisible: boolean;
- loading: boolean;
- /**
- * The number of actions that are not in the overflow menu.
- */
- numActionsVisible: number;
- };
- class SmartSearchBar extends React.Component<Props, State> {
- static defaultProps = {
- defaultQuery: '',
- query: null,
- onSearch: function () {},
- excludeEnvironment: false,
- placeholder: t('Search for events, users, tags, and more'),
- supportedTags: {},
- defaultSearchItems: [[], []],
- useFormWrapper: true,
- savedSearchType: SavedSearchType.ISSUE,
- };
- state: State = {
- query: this.initialQuery,
- parsedQuery: parseSearch(this.initialQuery),
- searchTerm: '',
- searchGroups: [],
- flatSearchItems: [],
- activeSearchItem: -1,
- tags: {},
- dropdownVisible: false,
- loading: false,
- numActionsVisible: this.props.actionBarItems?.length ?? 0,
- };
- componentDidMount() {
- if (!window.ResizeObserver) {
- return;
- }
- if (this.containerRef.current === null) {
- return;
- }
- this.inputResizeObserver = new ResizeObserver(this.updateActionsVisible);
- this.inputResizeObserver.observe(this.containerRef.current);
- }
- componentDidUpdate(prevProps: Props) {
- const {query} = this.props;
- const {query: lastQuery} = prevProps;
- if (query !== lastQuery && defined(query)) {
- // eslint-disable-next-line react/no-did-update-set-state
- this.setState(makeQueryState(addSpace(query)));
- }
- }
- componentWillUnmount() {
- this.inputResizeObserver?.disconnect();
- if (this.blurTimeout) {
- clearTimeout(this.blurTimeout);
- }
- }
- get initialQuery() {
- const {query, defaultQuery} = this.props;
- return query !== null ? addSpace(query) : defaultQuery ?? '';
- }
- /**
- * Tracks the dropdown blur
- */
- blurTimeout?: number;
- /**
- * Ref to the search element itself
- */
- searchInput = React.createRef<HTMLTextAreaElement>();
- /**
- * Ref to the search container
- */
- containerRef = React.createRef<HTMLDivElement>();
- /**
- * Used to determine when actions should be moved to the action overflow menu
- */
- inputResizeObserver: ResizeObserver | null = null;
- /**
- * Updates the numActionsVisible count as the search bar is resized
- */
- updateActionsVisible = (entries: ResizeObserverEntry[]) => {
- if (entries.length === 0) {
- return;
- }
- const entry = entries[0];
- const {width} = entry.contentRect;
- const actionCount = this.props.actionBarItems?.length ?? 0;
- const numActionsVisible = Math.min(
- actionCount,
- Math.floor(Math.max(0, width - ACTION_OVERFLOW_WIDTH) / ACTION_OVERFLOW_STEPS)
- );
- if (this.state.numActionsVisible === numActionsVisible) {
- return;
- }
- this.setState({numActionsVisible});
- };
- blur() {
- if (!this.searchInput.current) {
- return;
- }
- this.searchInput.current.blur();
- }
- async doSearch() {
- const {onSearch, onSavedRecentSearch, api, organization, savedSearchType} =
- this.props;
- this.blur();
- const query = removeSpace(this.state.query);
- callIfFunction(onSearch, query);
- // Only save recent search query if we have a savedSearchType (also 0 is a valid value)
- // Do not save empty string queries (i.e. if they clear search)
- if (typeof savedSearchType === 'undefined' || !query) {
- return;
- }
- try {
- await saveRecentSearch(api, organization.slug, savedSearchType, query);
- if (onSavedRecentSearch) {
- onSavedRecentSearch(query);
- }
- } catch (err) {
- // Silently capture errors if it fails to save
- Sentry.captureException(err);
- }
- }
- onSubmit = (evt: React.FormEvent) => {
- const {organization, savedSearchType} = this.props;
- evt.preventDefault();
- trackAnalyticsEvent({
- eventKey: 'search.searched',
- eventName: 'Search: Performed search',
- organization_id: organization.id,
- query: removeSpace(this.state.query),
- search_type: savedSearchType === 0 ? 'issues' : 'events',
- search_source: 'main_search',
- });
- this.doSearch();
- };
- clearSearch = () =>
- this.setState(makeQueryState(''), () =>
- callIfFunction(this.props.onSearch, this.state.query)
- );
- onQueryFocus = () => this.setState({dropdownVisible: true});
- onQueryBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
- // wait before closing dropdown in case blur was a result of clicking a
- // menu option
- const value = e.target.value;
- const blurHandler = () => {
- this.blurTimeout = undefined;
- this.setState({dropdownVisible: false});
- callIfFunction(this.props.onBlur, value);
- };
- this.blurTimeout = window.setTimeout(blurHandler, DROPDOWN_BLUR_DURATION);
- };
- onQueryChange = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {
- const query = evt.target.value.replace('\n', '');
- this.setState(makeQueryState(query), this.updateAutoCompleteItems);
- callIfFunction(this.props.onChange, evt.target.value, evt);
- };
- onInputClick = () => this.updateAutoCompleteItems();
- /**
- * Handle keyboard navigation
- */
- onKeyDown = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
- const {onKeyDown} = this.props;
- const {key} = evt;
- callIfFunction(onKeyDown, evt);
- if (!this.state.searchGroups.length) {
- return;
- }
- const isSelectingDropdownItems = this.state.activeSearchItem !== -1;
- if (key === 'ArrowDown' || key === 'ArrowUp') {
- evt.preventDefault();
- const {flatSearchItems, activeSearchItem} = this.state;
- const searchGroups = [...this.state.searchGroups];
- const [groupIndex, childrenIndex] = isSelectingDropdownItems
- ? filterSearchGroupsByIndex(searchGroups, activeSearchItem)
- : [];
- // Remove the previous 'active' property
- if (typeof groupIndex !== 'undefined') {
- if (
- childrenIndex !== undefined &&
- searchGroups[groupIndex]?.children?.[childrenIndex]
- ) {
- delete searchGroups[groupIndex].children[childrenIndex].active;
- }
- }
- const currIndex = isSelectingDropdownItems ? activeSearchItem : 0;
- const totalItems = flatSearchItems.length;
- // Move the selected index up/down
- const nextActiveSearchItem =
- key === 'ArrowUp'
- ? (currIndex - 1 + totalItems) % totalItems
- : isSelectingDropdownItems
- ? (currIndex + 1) % totalItems
- : 0;
- const [nextGroupIndex, nextChildrenIndex] = filterSearchGroupsByIndex(
- searchGroups,
- nextActiveSearchItem
- );
- // Make sure search items exist (e.g. both groups could be empty) and
- // attach the 'active' property to the item
- if (
- nextGroupIndex !== undefined &&
- nextChildrenIndex !== undefined &&
- searchGroups[nextGroupIndex]?.children
- ) {
- searchGroups[nextGroupIndex].children[nextChildrenIndex] = {
- ...searchGroups[nextGroupIndex].children[nextChildrenIndex],
- active: true,
- };
- }
- this.setState({searchGroups, activeSearchItem: nextActiveSearchItem});
- }
- if ((key === 'Tab' || key === 'Enter') && isSelectingDropdownItems) {
- evt.preventDefault();
- const {activeSearchItem, searchGroups} = this.state;
- const [groupIndex, childrenIndex] = filterSearchGroupsByIndex(
- searchGroups,
- activeSearchItem
- );
- const item =
- groupIndex !== undefined &&
- childrenIndex !== undefined &&
- searchGroups[groupIndex].children[childrenIndex];
- if (item && !isDefaultDropdownItem(item)) {
- this.onAutoComplete(item.value, item);
- }
- return;
- }
- if (key === 'Enter' && !isSelectingDropdownItems) {
- this.doSearch();
- return;
- }
- };
- onKeyUp = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
- // Other keys are managed at onKeyDown function
- if (evt.key !== 'Escape') {
- return;
- }
- evt.preventDefault();
- const isSelectingDropdownItems = this.state.activeSearchItem > -1;
- if (!isSelectingDropdownItems) {
- this.blur();
- return;
- }
- const {searchGroups, activeSearchItem} = this.state;
- const [groupIndex, childrenIndex] = isSelectingDropdownItems
- ? filterSearchGroupsByIndex(searchGroups, activeSearchItem)
- : [];
- if (groupIndex !== undefined && childrenIndex !== undefined) {
- delete searchGroups[groupIndex].children[childrenIndex].active;
- }
- this.setState({
- activeSearchItem: -1,
- searchGroups: [...this.state.searchGroups],
- });
- };
- getCursorPosition() {
- if (!this.searchInput.current) {
- return -1;
- }
- return this.searchInput.current.selectionStart ?? -1;
- }
- /**
- * Returns array of possible key values that substring match `query`
- */
- getTagKeys(query: string): SearchItem[] {
- const {prepareQuery} = this.props;
- const supportedTags = this.props.supportedTags ?? {};
- // Return all if query is empty
- let tagKeys = Object.keys(supportedTags).map(key => `${key}:`);
- if (query) {
- const preparedQuery =
- typeof prepareQuery === 'function' ? prepareQuery(query) : query;
- tagKeys = tagKeys.filter(key => key.indexOf(preparedQuery) > -1);
- }
- // If the environment feature is active and excludeEnvironment = true
- // then remove the environment key
- if (this.props.excludeEnvironment) {
- tagKeys = tagKeys.filter(key => key !== 'environment:');
- }
- return tagKeys.map(value => ({value, desc: value}));
- }
- /**
- * Returns array of tag values that substring match `query`; invokes `callback`
- * with data when ready
- */
- getTagValues = debounce(
- async (tag: Tag, query: string) => {
- // Strip double quotes if there are any
- query = query.replace(/"/g, '').trim();
- if (!this.props.onGetTagValues) {
- return [];
- }
- if (
- this.state.noValueQuery !== undefined &&
- query.startsWith(this.state.noValueQuery)
- ) {
- return [];
- }
- const {location} = this.props;
- const endpointParams = getParams(location.query);
- this.setState({loading: true});
- let values: string[] = [];
- try {
- values = await this.props.onGetTagValues(tag, query, endpointParams);
- this.setState({loading: false});
- } catch (err) {
- this.setState({loading: false});
- Sentry.captureException(err);
- return [];
- }
- if (tag.key === 'release:' && !values.includes('latest')) {
- values.unshift('latest');
- }
- const noValueQuery = values.length === 0 && query.length > 0 ? query : undefined;
- this.setState({noValueQuery});
- return values.map(value => {
- // Wrap in quotes if there is a space
- const escapedValue =
- value.includes(' ') || value.includes('"')
- ? `"${value.replace(/"/g, '\\"')}"`
- : value;
- return {value: escapedValue, desc: escapedValue, type: 'tag-value' as ItemType};
- });
- },
- DEFAULT_DEBOUNCE_DURATION,
- {leading: true}
- );
- /**
- * Returns array of tag values that substring match `query`; invokes `callback`
- * with results
- */
- getPredefinedTagValues = (tag: Tag, query: string): SearchItem[] =>
- (tag.values ?? [])
- .filter(value => value.indexOf(query) > -1)
- .map((value, i) => ({
- value,
- desc: value,
- type: 'tag-value',
- ignoreMaxSearchItems: tag.maxSuggestedValues ? i < tag.maxSuggestedValues : false,
- }));
- /**
- * Get recent searches
- */
- getRecentSearches = debounce(
- async () => {
- const {savedSearchType, hasRecentSearches, onGetRecentSearches} = this.props;
- // `savedSearchType` can be 0
- if (!defined(savedSearchType) || !hasRecentSearches) {
- return [];
- }
- const fetchFn = onGetRecentSearches || this.fetchRecentSearches;
- return await fetchFn(this.state.query);
- },
- DEFAULT_DEBOUNCE_DURATION,
- {leading: true}
- );
- fetchRecentSearches = async (fullQuery: string): Promise<SearchItem[]> => {
- const {api, organization, savedSearchType} = this.props;
- if (savedSearchType === undefined) {
- return [];
- }
- try {
- const recentSearches: any[] = await fetchRecentSearches(
- api,
- organization.slug,
- savedSearchType,
- fullQuery
- );
- // If `recentSearches` is undefined or not an array, the function will
- // return an array anyway
- return recentSearches.map(searches => ({
- desc: searches.query,
- value: searches.query,
- type: 'recent-search',
- }));
- } catch (e) {
- Sentry.captureException(e);
- }
- return [];
- };
- getReleases = debounce(
- async (tag: Tag, query: string) => {
- const releasePromise = this.fetchReleases(query);
- const tags = this.getPredefinedTagValues(tag, query);
- const tagValues = tags.map<SearchItem>(v => ({
- ...v,
- type: 'first-release',
- }));
- const releases = await releasePromise;
- const releaseValues = releases.map<SearchItem>((r: any) => ({
- value: r.shortVersion,
- desc: r.shortVersion,
- type: 'first-release',
- }));
- return [...tagValues, ...releaseValues];
- },
- DEFAULT_DEBOUNCE_DURATION,
- {leading: true}
- );
- /**
- * Fetches latest releases from a organization/project. Returns an empty array
- * if an error is encountered.
- */
- fetchReleases = async (releaseVersion: string): Promise<any[]> => {
- const {api, location, organization} = this.props;
- const project = location && location.query ? location.query.projectId : undefined;
- const url = `/organizations/${organization.slug}/releases/`;
- const fetchQuery: {[key: string]: string | number} = {
- per_page: MAX_AUTOCOMPLETE_RELEASES,
- };
- if (releaseVersion) {
- fetchQuery.query = releaseVersion;
- }
- if (project) {
- fetchQuery.project = project;
- }
- try {
- return await api.requestPromise(url, {
- method: 'GET',
- query: fetchQuery,
- });
- } catch (e) {
- addErrorMessage(t('Unable to fetch releases'));
- Sentry.captureException(e);
- }
- return [];
- };
- updateAutoCompleteItems = async () => {
- if (this.blurTimeout) {
- clearTimeout(this.blurTimeout);
- this.blurTimeout = undefined;
- }
- const cursor = this.getCursorPosition();
- let query = this.state.query;
- // Don't continue if the query hasn't changed
- if (query === this.state.previousQuery) {
- return;
- }
- this.setState({previousQuery: query});
- const lastTermIndex = getLastTermIndex(query, cursor);
- const terms = getQueryTerms(query, lastTermIndex);
- if (
- !terms || // no terms
- terms.length === 0 || // no terms
- (terms.length === 1 && terms[0] === this.props.defaultQuery) || // default term
- /^\s+$/.test(query.slice(cursor - 1, cursor + 1))
- ) {
- const [defaultSearchItems, defaultRecentItems] = this.props.defaultSearchItems!;
- if (!defaultSearchItems.length) {
- // Update searchTerm, otherwise <SearchDropdown> will have wrong state
- // (e.g. if you delete a query, the last letter will be highlighted if `searchTerm`
- // does not get updated)
- this.setState({searchTerm: query});
- const tagKeys = this.getTagKeys('');
- const recentSearches = await this.getRecentSearches();
- this.updateAutoCompleteState(tagKeys, recentSearches ?? [], '', 'tag-key');
- return;
- }
- // cursor on whitespace show default "help" search terms
- this.setState({searchTerm: ''});
- this.updateAutoCompleteState(defaultSearchItems, defaultRecentItems, '', 'default');
- return;
- }
- const last = terms.pop() ?? '';
- let autoCompleteItems: SearchItem[];
- let matchValue: string;
- let tagName: string;
- const index = last.indexOf(':');
- if (index === -1) {
- // No colon present; must still be deciding key
- matchValue = last.replace(new RegExp(`^${NEGATION_OPERATOR}`), '');
- autoCompleteItems = this.getTagKeys(matchValue);
- const recentSearches = await this.getRecentSearches();
- this.setState({searchTerm: matchValue});
- this.updateAutoCompleteState(
- autoCompleteItems,
- recentSearches ?? [],
- matchValue,
- 'tag-key'
- );
- return;
- }
- const {prepareQuery, excludeEnvironment} = this.props;
- const supportedTags = this.props.supportedTags ?? {};
- // TODO(billy): Better parsing for these examples
- //
- // > sentry:release:
- // > url:"http://with/colon"
- tagName = last.slice(0, index);
- // e.g. given "!gpu" we want "gpu"
- tagName = tagName.replace(new RegExp(`^${NEGATION_OPERATOR}`), '');
- query = last.slice(index + 1);
- const preparedQuery =
- typeof prepareQuery === 'function' ? prepareQuery(query) : query;
- // filter existing items immediately, until API can return
- // with actual tag value results
- const filteredSearchGroups = !preparedQuery
- ? this.state.searchGroups
- : this.state.searchGroups.filter(
- item => item.value && item.value.indexOf(preparedQuery) !== -1
- );
- this.setState({
- searchTerm: query,
- searchGroups: filteredSearchGroups,
- });
- const tag = supportedTags[tagName];
- if (!tag) {
- this.updateAutoCompleteState([], [], tagName, 'invalid-tag');
- return;
- }
- // Ignore the environment tag if the feature is active and
- // excludeEnvironment = true
- if (excludeEnvironment && tagName === 'environment') {
- return;
- }
- const fetchTagValuesFn =
- tag.key === 'firstRelease'
- ? this.getReleases
- : tag.predefined
- ? this.getPredefinedTagValues
- : this.getTagValues;
- const [tagValues, recentSearches] = await Promise.all([
- fetchTagValuesFn(tag, preparedQuery),
- this.getRecentSearches(),
- ]);
- this.updateAutoCompleteState(
- tagValues ?? [],
- recentSearches ?? [],
- tag.key,
- 'tag-value'
- );
- return;
- };
- /**
- * Updates autocomplete dropdown items and autocomplete index state
- *
- * @param searchItems List of search item objects with keys: title, desc, value
- * @param recentSearchItems List of recent search items, same format as searchItem
- * @param tagName The current tag name in scope
- * @param type Defines the type/state of the dropdown menu items
- */
- updateAutoCompleteState(
- searchItems: SearchItem[],
- recentSearchItems: SearchItem[],
- tagName: string,
- type: ItemType
- ) {
- const {hasRecentSearches, maxSearchItems, maxQueryLength} = this.props;
- const query = this.state.query;
- const queryCharsLeft =
- maxQueryLength && query ? maxQueryLength - query.length : undefined;
- this.setState(
- createSearchGroups(
- searchItems,
- hasRecentSearches ? recentSearchItems : undefined,
- tagName,
- type,
- maxSearchItems,
- queryCharsLeft
- )
- );
- }
- onAutoComplete = (replaceText: string, item: SearchItem) => {
- if (item.type === 'recent-search') {
- trackAnalyticsEvent({
- eventKey: 'search.searched',
- eventName: 'Search: Performed search',
- organization_id: this.props.organization.id,
- query: replaceText,
- source: this.props.savedSearchType === 0 ? 'issues' : 'events',
- search_source: 'recent_search',
- });
- this.setState(makeQueryState(replaceText), () => {
- // Propagate onSearch and save to recent searches
- this.doSearch();
- });
- return;
- }
- const cursor = this.getCursorPosition();
- const query = this.state.query;
- const lastTermIndex = getLastTermIndex(query, cursor);
- const terms = getQueryTerms(query, lastTermIndex);
- let newQuery: string;
- // If not postfixed with : (tag value), add trailing space
- replaceText += item.type !== 'tag-value' || cursor < query.length ? '' : ' ';
- const isNewTerm = query.charAt(query.length - 1) === ' ' && item.type !== 'tag-value';
- if (!terms) {
- newQuery = replaceText;
- } else if (isNewTerm) {
- newQuery = `${query}${replaceText}`;
- } else {
- const last = terms.pop() ?? '';
- newQuery = query.slice(0, lastTermIndex); // get text preceding last term
- const prefix = last.startsWith(NEGATION_OPERATOR) ? NEGATION_OPERATOR : '';
- // newQuery is all the terms up to the current term: "... <term>:"
- // replaceText should be the selected value
- if (last.indexOf(':') > -1) {
- let replacement = `:${replaceText}`;
- // The user tag often contains : within its value and we need to quote it.
- if (last.startsWith('user:')) {
- const colonIndex = replaceText.indexOf(':');
- if (colonIndex > -1) {
- replacement = `:"${replaceText.trim()}"`;
- }
- }
- // tag key present: replace everything after colon with replaceText
- newQuery = newQuery.replace(/\:"[^"]*"?$|\:\S*$/, replacement);
- } else {
- // no tag key present: replace last token with replaceText
- newQuery = newQuery.replace(/\S+$/, `${prefix}${replaceText}`);
- }
- newQuery = newQuery.concat(query.slice(lastTermIndex));
- }
- this.setState(makeQueryState(newQuery), () => {
- // setting a new input value will lose focus; restore it
- if (this.searchInput.current) {
- this.searchInput.current.focus();
- }
- // then update the autocomplete box with new items
- this.updateAutoCompleteItems();
- this.props.onChange?.(newQuery, new MouseEvent('click') as any);
- });
- };
- render() {
- const {
- api,
- className,
- savedSearchType,
- dropdownClassName,
- actionBarItems,
- organization,
- placeholder,
- disabled,
- useFormWrapper,
- inlineLabel,
- maxQueryLength,
- } = this.props;
- const {
- query,
- parsedQuery,
- searchGroups,
- searchTerm,
- dropdownVisible,
- numActionsVisible,
- loading,
- } = this.state;
- const hasSyntaxHighlight = organization.features.includes('search-syntax-highlight');
- const input = (
- <SearchInput
- type="text"
- placeholder={placeholder}
- id="smart-search-input"
- name="query"
- ref={this.searchInput}
- autoComplete="off"
- value={query}
- onFocus={this.onQueryFocus}
- onBlur={this.onQueryBlur}
- onKeyUp={this.onKeyUp}
- onKeyDown={this.onKeyDown}
- onChange={this.onQueryChange}
- onClick={this.onInputClick}
- disabled={disabled}
- maxLength={maxQueryLength}
- spellCheck={false}
- />
- );
- // Segment actions into visible and overflowed groups
- const actionItems = actionBarItems ?? [];
- const actionProps = {
- api,
- organization,
- query,
- savedSearchType,
- };
- const visibleActions = actionItems
- .slice(0, numActionsVisible)
- .map(({key, Action}) => <Action key={key} {...actionProps} />);
- const overflowedActions = actionItems
- .slice(numActionsVisible)
- .map(({key, Action}) => <Action key={key} {...actionProps} menuItemVariant />);
- const cursor = this.getCursorPosition();
- return (
- <Container ref={this.containerRef} className={className} isOpen={dropdownVisible}>
- <SearchLabel htmlFor="smart-search-input" aria-label={t('Search events')}>
- <IconSearch />
- {inlineLabel}
- </SearchLabel>
- <InputWrapper>
- <Highlight>
- {hasSyntaxHighlight && parsedQuery !== null ? (
- <HighlightQuery
- parsedQuery={parsedQuery}
- cursorPosition={cursor === -1 ? undefined : cursor}
- />
- ) : (
- query
- )}
- </Highlight>
- {useFormWrapper ? <form onSubmit={this.onSubmit}>{input}</form> : input}
- </InputWrapper>
- <ActionsBar gap={0.5}>
- {query !== '' && (
- <ActionButton
- onClick={this.clearSearch}
- icon={<IconClose size="xs" />}
- title={t('Clear search')}
- aria-label={t('Clear search')}
- />
- )}
- {visibleActions}
- {overflowedActions.length > 0 && (
- <DropdownLink
- anchorRight
- caret={false}
- title={
- <ActionButton
- aria-label={t('Show more')}
- icon={<VerticalEllipsisIcon size="xs" />}
- />
- }
- >
- {overflowedActions}
- </DropdownLink>
- )}
- </ActionsBar>
- {(loading || searchGroups.length > 0) && (
- <SearchDropdown
- css={{display: dropdownVisible ? 'block' : 'none'}}
- className={dropdownClassName}
- items={searchGroups}
- onClick={this.onAutoComplete}
- loading={loading}
- searchSubstring={searchTerm}
- />
- )}
- </Container>
- );
- }
- }
- type ContainerState = {
- members: ReturnType<typeof MemberListStore.getAll>;
- };
- class SmartSearchBarContainer extends React.Component<Props, ContainerState> {
- state: ContainerState = {
- members: MemberListStore.getAll(),
- };
- componentWillUnmount() {
- this.unsubscribe();
- }
- unsubscribe = MemberListStore.listen(
- (members: ContainerState['members']) => this.setState({members}),
- undefined
- );
- render() {
- // SmartSearchBar doesn't use members, but we forward it to cause a re-render.
- return <SmartSearchBar {...this.props} members={this.state.members} />;
- }
- }
- export default withApi(withRouter(withOrganization(SmartSearchBarContainer)));
- export {SmartSearchBar};
- const Container = styled('div')<{isOpen: boolean}>`
- border: 1px solid ${p => p.theme.border};
- box-shadow: inset ${p => p.theme.dropShadowLight};
- background: ${p => p.theme.background};
- padding: 7px ${space(1)};
- position: relative;
- display: grid;
- grid-template-columns: max-content 1fr max-content;
- grid-gap: ${space(1)};
- align-items: start;
- border-radius: ${p =>
- p.isOpen
- ? `${p.theme.borderRadius} ${p.theme.borderRadius} 0 0`
- : p.theme.borderRadius};
- .show-sidebar & {
- background: ${p => p.theme.backgroundSecondary};
- }
- `;
- const SearchLabel = styled('label')`
- display: flex;
- padding: ${space(0.5)} 0;
- margin: 0;
- color: ${p => p.theme.gray300};
- `;
- const InputWrapper = styled('div')`
- position: relative;
- `;
- const Highlight = styled('div')`
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- user-select: none;
- white-space: pre-wrap;
- word-break: break-word;
- line-height: 25px;
- font-size: ${p => p.theme.fontSizeSmall};
- font-family: ${p => p.theme.text.familyMono};
- `;
- const SearchInput = styled(TextareaAutosize, {
- shouldForwardProp: prop => typeof prop === 'string' && isPropValid(prop),
- })`
- position: relative;
- display: flex;
- resize: none;
- outline: none;
- border: 0;
- width: 100%;
- padding: 0;
- line-height: 25px;
- margin-bottom: -1px;
- background: transparent;
- font-size: ${p => p.theme.fontSizeSmall};
- font-family: ${p => p.theme.text.familyMono};
- caret-color: ${p => p.theme.subText};
- color: transparent;
- &::selection {
- background: rgba(0, 0, 0, 0.2);
- }
- &::placeholder {
- color: ${p => p.theme.formPlaceholder};
- }
- [disabled] {
- color: ${p => p.theme.disabled};
- }
- `;
- const ActionsBar = styled(ButtonBar)`
- height: ${space(2)};
- margin: ${space(0.5)} 0;
- `;
- const VerticalEllipsisIcon = styled(IconEllipsis)`
- transform: rotate(90deg);
- `;
|