Skip to content

Commit

Permalink
fix issue that would deselect dataset
Browse files Browse the repository at this point in the history
Signed-off-by: Kawika Avilla <[email protected]>
  • Loading branch information
kavilla committed Aug 25, 2024
1 parent 89e238c commit 2323d10
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 53 deletions.
49 changes: 27 additions & 22 deletions src/plugins/data/public/ui/dataset_selector/dataset_selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import React, { useEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
EuiButtonEmpty,
EuiIcon,
Expand Down Expand Up @@ -33,7 +33,6 @@ export const DatasetSelector = ({
}: DatasetSelectorProps) => {
const [isOpen, setIsOpen] = useState(false);
const [datasets, setDatasets] = useState<Dataset[]>([]);
const togglePopover = () => setIsOpen(!isOpen);
const closePopover = () => setIsOpen(false);
const { overlays, savedObjects } = services;

Expand All @@ -42,19 +41,23 @@ export const DatasetSelector = ({
const datasetIcon =
datasetService.getType(selectedDataset?.type || '')?.meta.icon.type || 'database';

const fetchDatasets = useCallback(async () => {
const fetchedDatasets = await datasetService
.getType(DEFAULT_DATA.SET_TYPES.INDEX_PATTERN)
?.fetch(savedObjects.client, []);
setDatasets(fetchedDatasets?.children || []);
}, [datasetService, savedObjects.client]);

useEffect(() => {
const init = async () => {
setDatasets(
(
await datasetService
.getType(DEFAULT_DATA.SET_TYPES.INDEX_PATTERN)
?.fetch(savedObjects.client, [])!
).children || []
);
};
fetchDatasets();
}, [fetchDatasets]);

init();
}, [datasetService, savedObjects.client]);
const togglePopover = useCallback(async () => {
if (!isOpen) {
await fetchDatasets();
}
setIsOpen(!isOpen);
}, [isOpen, fetchDatasets]);

const options = useMemo(() => {
const newOptions: EuiSelectableOption[] = [];
Expand All @@ -76,19 +79,21 @@ export const DatasetSelector = ({
return newOptions;
}, [datasets, selectedDataset?.id, datasetService]);

// Handle option change
const handleOptionChange = (newOptions: EuiSelectableOption[]) => {
const selectedOption = newOptions.find((option) => option.checked === 'on');

if (!selectedOption) {
setSelectedDataset(undefined);
return;
if (selectedOption) {
const foundDataset = datasets.find((dataset) => dataset.id === selectedOption.key);
if (foundDataset) {
closePopover();
setSelectedDataset(foundDataset);
}
} else {
// Only clear the selection if there was a previously selected dataset
if (selectedDataset) {
setSelectedDataset(undefined);
}
}

const foundDataset = datasets.find((dataset) => dataset.id === selectedOption.key);

closePopover();
setSelectedDataset(foundDataset || undefined);
};

return (
Expand Down
32 changes: 20 additions & 12 deletions src/plugins/data/public/ui/query_editor/query_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ import { Settings } from '..';
import { IDataPluginServices, IFieldType, IIndexPattern, Query, TimeRange } from '../..';
import { OpenSearchDashboardsReactContextValue } from '../../../../opensearch_dashboards_react/public';
import { QuerySuggestion } from '../../autocomplete';
import { fromUser, getQueryLog, LanguageConfig, PersistedLog, toUser } from '../../query';
import { fromUser, getQueryLog, PersistedLog, toUser } from '../../query';
import { SuggestionsListSize } from '../typeahead/suggestions_component';
import { DataSettings } from '../types';
import { QueryLanguageSelector } from './language_selector';
import { QueryEditorExtensions } from './query_editor_extensions';
import { QueryEditorBtnCollapse } from './query_editor_btn_collapse';
import { Dataset } from '../../../common';
import { createDQLEditor, createDefaultEditor } from './editors';
import { getQueryService, getIndexPatterns } from '../../services';
import { DatasetSelector } from '../dataset_selector';
Expand All @@ -30,7 +29,6 @@ const LANGUAGE_ID_KUERY = 'kuery';
monaco.languages.register({ id: LANGUAGE_ID_KUERY });

export interface QueryEditorProps {
dataset?: Dataset;
query: Query;
settings: Settings;
disableAutoFocus?: boolean;
Expand All @@ -44,12 +42,10 @@ export interface QueryEditorProps {
onChange?: (query: Query, dateRange?: TimeRange) => void;
onChangeQueryEditorFocus?: (isFocused: boolean) => void;
onSubmit?: (query: Query, dateRange?: TimeRange) => void;
getQueryStringInitialValue?: (language: LanguageConfig) => string;
dataTestSubj?: string;
size?: SuggestionsListSize;
className?: string;
isInvalid?: boolean;
queryLanguage?: string;
headerClassName?: string;
bannerClassName?: string;
footerClassName?: string;
Expand Down Expand Up @@ -111,7 +107,7 @@ export default class QueryEditorUI extends Component<Props, State> {
!(
this.headerRef.current &&
this.bannerRef.current &&
this.props.queryLanguage &&
this.props.query.language &&
this.extensionMap &&
Object.keys(this.extensionMap).length > 0
)
Expand All @@ -120,7 +116,7 @@ export default class QueryEditorUI extends Component<Props, State> {
}
return (
<QueryEditorExtensions
language={this.props.queryLanguage}
language={this.props.query.language}
onSelectLanguage={this.onSelectLanguage}
isCollapsed={this.state.isCollapsed}
setIsCollapsed={this.setIsCollapsed}
Expand All @@ -137,13 +133,20 @@ export default class QueryEditorUI extends Component<Props, State> {
this.persistedLog.add(query.query);
}

this.props.onSubmit({ query: fromUser(query.query), language: query.language });
this.props.onSubmit({
query: fromUser(query.query),
language: query.language,
dataset: query.dataset,
});
}
};

private onChange = (query: Query, dateRange?: TimeRange) => {
if (this.props.onChange) {
this.props.onChange({ query: fromUser(query.query), language: query.language }, dateRange);
this.props.onChange(
{ query: fromUser(query.query), language: query.language, dataset: query.dataset },
dateRange
);
}
};

Expand All @@ -153,7 +156,11 @@ export default class QueryEditorUI extends Component<Props, State> {
index: null,
});

this.onChange({ query: value, language: this.props.query.language });
this.onChange({
query: value,
language: this.props.query.language,
dataset: this.props.query.dataset,
});
};

private onInputChange = (value: string) => {
Expand Down Expand Up @@ -245,7 +252,8 @@ export default class QueryEditorUI extends Component<Props, State> {
private fetchIndexPattern = async () => {
const dataset = this.queryString.getQuery().dataset;
if (!dataset) return undefined;
return getIndexPatterns().getByTitle(dataset.title);
const indexPattern = await getIndexPatterns().get(dataset.id);
return indexPattern;
};

provideCompletionItems = async (
Expand Down Expand Up @@ -317,7 +325,7 @@ export default class QueryEditorUI extends Component<Props, State> {
footerItems: {
start: [
`${this.state.lineCount} ${this.state.lineCount === 1 ? 'line' : 'lines'}`,
this.props.dataset?.timeFieldName || '',
this.props.query.dataset?.timeFieldName || '',
],
},
provideCompletionItems: this.provideCompletionItems,
Expand Down
32 changes: 13 additions & 19 deletions src/plugins/data/public/ui/query_editor/query_editor_top_row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,19 @@ export default function QueryEditorTopRow(props: QueryEditorTopRowProps) {
},
} = opensearchDashboards.services;

const language = props.query && props.query.language;
const parsedQuery =
!language || isValidQuery(props.query) ? props.query! : queryString.getInitialQuery();
if (!isEqual(parsedQuery?.query, props.query?.query)) {
onQueryChange(parsedQuery);
onSubmit({ query: parsedQuery, dateRange: getDateRange() });
}
const queryLanguage = props.query && props.query.language;
// const parsedQuery =
// !language || isValidQuery(props.query) ? props.query! : queryString.getInitialQuery();
// if (!isEqual(parsedQuery?.query, props.query?.query)) {
// onQueryChange(parsedQuery);
// onSubmit({ query: parsedQuery, dateRange: getDateRange() });
// }
const persistedLog: PersistedLog | undefined = React.useMemo(
() =>
language && uiSettings && storage && appName
? getQueryLog(uiSettings!, storage, appName, language!)
queryLanguage && uiSettings && storage && appName
? getQueryLog(uiSettings!, storage, appName, queryLanguage)
: undefined,
[language, uiSettings, storage, appName]
[queryLanguage, uiSettings, storage, appName]
);

function onClickSubmitButton(event: React.MouseEvent<HTMLButtonElement>) {
Expand All @@ -98,7 +98,7 @@ export default function QueryEditorTopRow(props: QueryEditorTopRowProps) {

function getDateRange() {
const defaultTimeSetting = uiSettings!.get(UI_SETTINGS.TIMEPICKER_TIME_DEFAULTS);
const languageConfig = queryString.getLanguageService().getLanguage(language!);
const languageConfig = queryString.getLanguageService().getLanguage(queryLanguage!);
return {
from:
props.dateRangeFrom ||
Expand All @@ -112,8 +112,6 @@ export default function QueryEditorTopRow(props: QueryEditorTopRowProps) {
}

function onQueryChange(query: Query, dateRange?: TimeRange) {
const languageConfig = queryString.getLanguageService().getLanguage(language!);
if (languageConfig && !isValidQuery(query)) return;
props.onChange({
query,
dateRange: dateRange ?? getDateRange(),
Expand Down Expand Up @@ -186,18 +184,14 @@ export default function QueryEditorTopRow(props: QueryEditorTopRowProps) {
return valueAsMoment.toISOString();
}

function isValidQuery(query: Query | undefined) {
if (query && query.query) return true;
}

function renderQueryEditor() {
if (!shouldRenderQueryEditor()) return;
return (
<EuiFlexItem>
<QueryEditor
disableAutoFocus={props.disableAutoFocus}
queryActions={props.prepend}
query={parsedQuery}
query={props.query!}
settings={props.settings!}
screenTitle={props.screenTitle}
onChange={onQueryChange}
Expand Down Expand Up @@ -229,7 +223,7 @@ export default function QueryEditorTopRow(props: QueryEditorTopRowProps) {
}

function shouldRenderDatePicker(): boolean {
const languageConfig = queryString.getLanguageService().getLanguage(language!);
const languageConfig = queryString.getLanguageService().getLanguage(queryLanguage!);
return Boolean(
(props.showDatePicker && (languageConfig?.searchBar?.showDatePicker ?? true)) ??
(props.showAutoRefreshOnly && (languageConfig?.searchBar?.showAutoRefreshOnly ?? true))
Expand Down
12 changes: 12 additions & 0 deletions src/plugins/data/public/ui/search_bar/search_bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ class SearchBarUI extends Component<SearchBarProps, State> {
nextQuery = {
query: nextProps.query.query,
language: nextProps.query.language,
dataset: nextProps.query.dataset,
};
} else if (
nextProps.query &&
Expand All @@ -144,6 +145,17 @@ class SearchBarUI extends Component<SearchBarProps, State> {
nextQuery = {
query: '',
language: nextProps.query.language,
dataset: nextProps.query.dataset,
};
} else if (
nextProps.query &&
prevState.query &&
nextProps.query.dataset !== prevState.query.dataset
) {
nextQuery = {
query: nextProps.query.query,
language: nextProps.query.language,
dataset: nextProps.query.dataset,
};
}

Expand Down

0 comments on commit 2323d10

Please sign in to comment.