feat(dashboard): View query of the chart in dashboard (#14667)

* Extract view query component out

* Typo correction

* Fix and rename tests

* Remove logs, and test code

* Rename file - fix tests

* Fix a typo

* Linting errors, add Apache License Header
This commit is contained in:
Ajay M 2021-05-18 16:17:11 -04:00 committed by GitHub
parent a7a011cce5
commit 84e8dc71f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 178 additions and 126 deletions

View File

@ -20,9 +20,9 @@ import React from 'react';
import { mount, shallow } from 'enzyme';
import { supersetTheme, ThemeProvider } from '@superset-ui/core';
import { Dropdown, Menu } from 'src/common/components';
import { DisplayQueryButton } from 'src/explore/components/DisplayQueryButton';
import ExploreAdditionalActionsMenu from 'src/explore/components/ExploreAdditionalActionsMenu';
describe('DisplayQueryButton', () => {
describe('ExploreAdditionalActionsMenu', () => {
const defaultProps = {
animation: false,
queryResponse: {
@ -38,12 +38,12 @@ describe('DisplayQueryButton', () => {
};
it('is valid', () => {
expect(React.isValidElement(<DisplayQueryButton {...defaultProps} />)).toBe(
true,
);
expect(
React.isValidElement(<ExploreAdditionalActionsMenu {...defaultProps} />),
).toBe(true);
});
it('renders a dropdown with 3 itens', () => {
const wrapper = mount(<DisplayQueryButton {...defaultProps} />, {
it('renders a dropdown with 3 items', () => {
const wrapper = mount(<ExploreAdditionalActionsMenu {...defaultProps} />, {
wrappingComponent: ThemeProvider,
wrappingComponentProps: {
theme: supersetTheme,

View File

@ -157,6 +157,7 @@ const createProps = () => ({
forceRefresh: jest.fn(),
exploreChart: jest.fn(),
exportCSV: jest.fn(),
formData: {},
});
test('Should render', () => {

View File

@ -56,10 +56,11 @@ type SliceHeaderProps = {
addDangerToast: Function;
handleToggleFullSize: Function;
chartStatus: string;
formData: object;
};
const annoationsLoading = t('Annotation layers are still loading.');
const annoationsError = t('One ore more annotation layers failed loading.');
const annotationsLoading = t('Annotation layers are still loading.');
const annotationsError = t('One ore more annotation layers failed loading.');
const CrossFilterIcon = styled(Icon)`
fill: ${({ theme }) => theme.colors.grayscale.light5};
@ -95,6 +96,7 @@ const SliceHeader: FC<SliceHeaderProps> = ({
handleToggleFullSize,
isFullSize,
chartStatus,
formData,
}) => {
// TODO: change to indicator field after it will be implemented
const crossFilterValue = useSelector<RootState, any>(
@ -120,11 +122,11 @@ const SliceHeader: FC<SliceHeaderProps> = ({
<Tooltip
id="annotations-loading-tooltip"
placement="top"
title={annoationsLoading}
title={annotationsLoading}
>
<i
role="img"
aria-label={annoationsLoading}
aria-label={annotationsLoading}
className="fa fa-refresh warning"
/>
</Tooltip>
@ -133,11 +135,11 @@ const SliceHeader: FC<SliceHeaderProps> = ({
<Tooltip
id="annoation-errors-tooltip"
placement="top"
title={annoationsError}
title={annotationsError}
>
<i
role="img"
aria-label={annoationsError}
aria-label={annotationsError}
className="fa fa-exclamation-circle danger"
/>
</Tooltip>
@ -183,6 +185,7 @@ const SliceHeader: FC<SliceHeaderProps> = ({
handleToggleFullSize={handleToggleFullSize}
isFullSize={isFullSize}
chartStatus={chartStatus}
formData={formData}
/>
</>
)}

View File

@ -33,6 +33,8 @@ import { getActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
import CrossFilterScopingModal from 'src/dashboard/components/CrossFilterScopingModal/CrossFilterScopingModal';
import Icons from 'src/components/Icons';
import ModalTrigger from 'src/components/ModalTrigger';
import ViewQueryModal from 'src/explore/components/controls/ViewQueryModal';
const propTypes = {
slice: PropTypes.object.isRequired,
@ -76,6 +78,7 @@ const MENU_KEYS = {
EXPORT_CSV: 'export_csv',
RESIZE_LABEL: 'resize_label',
DOWNLOAD_AS_IMAGE: 'download_as_image',
VIEW_QUERY: 'view_query',
};
const VerticalDotsContainer = styled.div`
@ -256,6 +259,21 @@ class SliceHeaderControls extends React.PureComponent {
</Menu.Item>
)}
{this.props.supersetCanExplore && (
<Menu.Item key={MENU_KEYS.VIEW_QUERY}>
<ModalTrigger
triggerNode={
<span data-test="view-query-menu-item">{t('View query')}</span>
}
modalTitle={t('View query')}
modalBody={
<ViewQueryModal latestQueryFormData={this.props.formData} />
}
responsive
/>
</Menu.Item>
)}
{supersetCanShare && (
<ShareMenuItems
url={getDashboardUrl(

View File

@ -334,6 +334,7 @@ export default class Chart extends React.Component {
handleToggleFullSize={handleToggleFullSize}
isFullSize={isFullSize}
chartStatus={chart.chartStatus}
formData={formData}
/>
{/*

View File

@ -25,8 +25,8 @@ import copyTextToClipboard from 'src/utils/copy';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import { useUrlShortener } from 'src/common/hooks/useUrlShortener';
import EmbedCodeButton from './EmbedCodeButton';
import ConnectedDisplayQueryButton from './DisplayQueryButton';
import { exportChart, getExploreLongUrl } from '../exploreUtils';
import ExploreAdditionalActionsMenu from './ExploreAdditionalActionsMenu';
type ActionButtonProps = {
icon: React.ReactElement;
@ -39,7 +39,7 @@ type ActionButtonProps = {
};
type ExploreActionButtonsProps = {
actions: { redirectSQLLab: Function; openPropertiesModal: Function };
actions: { redirectSQLLab: () => void; openPropertiesModal: () => void };
canDownloadCSV: boolean;
chartStatus: string;
latestQueryFormData: {};
@ -90,7 +90,6 @@ const ExploreActionButtons = (props: ExploreActionButtonsProps) => {
canDownloadCSV,
chartStatus,
latestQueryFormData,
queriesResponse,
slice,
addDangerToast,
} = props;
@ -178,8 +177,7 @@ const ExploreActionButtons = (props: ExploreActionButtonsProps) => {
/>
</>
)}
<ConnectedDisplayQueryButton
queryResponse={queriesResponse?.[0]}
<ExploreAdditionalActionsMenu
latestQueryFormData={latestQueryFormData}
chartStatus={chartStatus}
onOpenInEditor={actions.redirectSQLLab}

View File

@ -23,7 +23,7 @@ import userEvent from '@testing-library/user-event';
import * as chartAction from 'src/chart/chartAction';
import * as downloadAsImage from 'src/utils/downloadAsImage';
import fetchMock from 'fetch-mock';
import ConectedDisplayQueryButton from '.';
import ExploreAdditionalActionsMenu from '.';
const createProps = () => ({
latestQueryFormData: {
@ -90,15 +90,15 @@ fetchMock.post(
},
);
test('Shoud render a button', () => {
test('Should render a button', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { useRedux: true });
render(<ExploreAdditionalActionsMenu {...props} />, { useRedux: true });
expect(screen.getByRole('button')).toBeInTheDocument();
});
test('Shoud open a menu', () => {
test('Should open a menu', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true,
});
@ -122,9 +122,9 @@ test('Shoud open a menu', () => {
).toBeInTheDocument();
});
test('Shoud call onOpenPropertiesModal when click on "Edit properties"', () => {
test('Should call onOpenPropertiesModal when click on "Edit properties"', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true,
});
expect(props.onOpenInEditor).toBeCalledTimes(0);
@ -133,10 +133,10 @@ test('Shoud call onOpenPropertiesModal when click on "Edit properties"', () => {
expect(props.onOpenPropertiesModal).toBeCalledTimes(1);
});
test('Shoud call getChartDataRequest when click on "View query"', async () => {
test('Should call getChartDataRequest when click on "View query"', async () => {
const props = createProps();
const getChartDataRequest = jest.spyOn(chartAction, 'getChartDataRequest');
render(<ConectedDisplayQueryButton {...props} />, {
render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true,
});
@ -150,9 +150,9 @@ test('Shoud call getChartDataRequest when click on "View query"', async () => {
await waitFor(() => expect(getChartDataRequest).toBeCalledTimes(1));
});
test('Shoud call onOpenInEditor when click on "Run in SQL Lab"', () => {
test('Should call onOpenInEditor when click on "Run in SQL Lab"', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true,
});
@ -164,10 +164,10 @@ test('Shoud call onOpenInEditor when click on "Run in SQL Lab"', () => {
expect(props.onOpenInEditor).toBeCalledTimes(1);
});
test('Shoud call downloadAsImage when click on "Download as image"', () => {
test('Should call downloadAsImage when click on "Download as image"', () => {
const props = createProps();
const spy = jest.spyOn(downloadAsImage, 'default');
render(<ConectedDisplayQueryButton {...props} />, {
render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true,
});

View File

@ -16,31 +16,16 @@
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState } from 'react';
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import htmlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars';
import markdownSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown';
import sqlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
import jsonSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/json';
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import { styled, t } from '@superset-ui/core';
import { t } from '@superset-ui/core';
import { Dropdown, Menu } from 'src/common/components';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import CopyToClipboard from 'src/components/CopyToClipboard';
import { getChartDataRequest } from 'src/chart/chartAction';
import downloadAsImage from 'src/utils/downloadAsImage';
import Loading from 'src/components/Loading';
import ModalTrigger from 'src/components/ModalTrigger';
import { sliceUpdated } from 'src/explore/actions/exploreActions';
import { CopyButton } from 'src/explore/components/DataTableControl';
SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
SyntaxHighlighter.registerLanguage('html', htmlSyntax);
SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
SyntaxHighlighter.registerLanguage('json', jsonSyntax);
import ViewQueryModal from '../controls/ViewQueryModal';
const propTypes = {
onOpenPropertiesModal: PropTypes.func,
@ -54,53 +39,12 @@ const MENU_KEYS = {
EDIT_PROPERTIES: 'edit_properties',
RUN_IN_SQL_LAB: 'run_in_sql_lab',
DOWNLOAD_AS_IMAGE: 'download_as_image',
VIEW_QUERY: 'view_query',
};
const CopyButtonViewQuery = styled(CopyButton)`
&& {
margin: 0 0 ${({ theme }) => theme.gridUnit}px;
}
`;
export const DisplayQueryButton = props => {
const ExploreAdditionalActionsMenu = props => {
const { datasource } = props.latestQueryFormData;
const [language, setLanguage] = useState(null);
const [query, setQuery] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [sqlSupported] = useState(
datasource && datasource.split('__')[1] === 'table',
);
const beforeOpen = resultType => {
setIsLoading(true);
getChartDataRequest({
formData: props.latestQueryFormData,
resultFormat: 'json',
resultType,
})
.then(response => {
// Only displaying the first query is currently supported
const result = response.result[0];
setLanguage(result.language);
setQuery(result.query);
setIsLoading(false);
setError(null);
})
.catch(response => {
getClientErrorObject(response).then(
({ error, message, statusText }) => {
setError(
error || message || statusText || t('Sorry, An error occurred'),
);
setIsLoading(false);
},
);
});
};
const sqlSupported = datasource && datasource.split('__')[1] === 'table';
const handleMenuClick = ({ key, domEvent }) => {
const { slice, onOpenInEditor, latestQueryFormData } = props;
switch (key) {
@ -124,34 +68,6 @@ export const DisplayQueryButton = props => {
}
};
const renderQueryModalBody = () => {
if (isLoading) {
return <Loading />;
}
if (error) {
return <pre>{error}</pre>;
}
if (query) {
return (
<div>
<CopyToClipboard
text={query}
shouldShowText={false}
copyNode={
<CopyButtonViewQuery buttonSize="xsmall">
<i className="fa fa-clipboard" />
</CopyButtonViewQuery>
}
/>
<SyntaxHighlighter language={language} style={github}>
{query}
</SyntaxHighlighter>
</div>
);
}
return null;
};
const { slice } = props;
return (
<Dropdown
@ -164,14 +80,17 @@ export const DisplayQueryButton = props => {
{t('Edit properties')}
</Menu.Item>
)}
<Menu.Item>
<Menu.Item key={MENU_KEYS.VIEW_QUERY}>
<ModalTrigger
triggerNode={
<span data-test="view-query-menu-item">{t('View query')}</span>
}
modalTitle={t('View query')}
beforeOpen={() => beforeOpen('query')}
modalBody={renderQueryModalBody()}
modalBody={
<ViewQueryModal
latestQueryFormData={props.latestQueryFormData}
/>
}
responsive
/>
</Menu.Item>
@ -198,10 +117,10 @@ export const DisplayQueryButton = props => {
);
};
DisplayQueryButton.propTypes = propTypes;
ExploreAdditionalActionsMenu.propTypes = propTypes;
function mapDispatchToProps(dispatch) {
return bindActionCreators({ sliceUpdated }, dispatch);
}
export default connect(null, mapDispatchToProps)(DisplayQueryButton);
export default connect(null, mapDispatchToProps)(ExploreAdditionalActionsMenu);

View File

@ -0,0 +1,112 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useEffect, useState } from 'react';
import { styled, t } from '@superset-ui/core';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import CopyToClipboard from 'src/components/CopyToClipboard';
import Loading from 'src/components/Loading';
import { CopyButton } from 'src/explore/components/DataTableControl';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { getChartDataRequest } from 'src/chart/chartAction';
import markdownSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown';
import htmlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars';
import sqlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
import jsonSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/json';
const CopyButtonViewQuery = styled(CopyButton)`
&& {
margin: 0 0 ${({ theme }) => theme.gridUnit}px;
}
`;
SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
SyntaxHighlighter.registerLanguage('html', htmlSyntax);
SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
SyntaxHighlighter.registerLanguage('json', jsonSyntax);
interface Props {
latestQueryFormData: object;
}
const ViewQueryModal: React.FC<Props> = props => {
const [language, setLanguage] = useState(null);
const [query, setQuery] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const loadChartData = (resultType: string) => {
setIsLoading(true);
getChartDataRequest({
formData: props.latestQueryFormData,
resultFormat: 'json',
resultType,
})
.then(response => {
// Only displaying the first query is currently supported
const result = response.result[0];
setLanguage(result.language);
setQuery(result.query);
setIsLoading(false);
setError(null);
})
.catch(response => {
getClientErrorObject(response).then(({ error, message }) => {
setError(
error ||
message ||
response.statusText ||
t('Sorry, An error occurred'),
);
setIsLoading(false);
});
});
};
useEffect(() => {
loadChartData('query');
}, [props.latestQueryFormData]);
if (isLoading) {
return <Loading />;
}
if (error) {
return <pre>{error}</pre>;
}
if (query) {
return (
<div>
<CopyToClipboard
text={query}
shouldShowText={false}
copyNode={
<CopyButtonViewQuery buttonSize="xsmall">
<i className="fa fa-clipboard" />
</CopyButtonViewQuery>
}
/>
<SyntaxHighlighter language={language || undefined} style={github}>
{query}
</SyntaxHighlighter>
</div>
);
}
return null;
};
export default ViewQueryModal;