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

View File

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

View File

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

View File

@ -33,6 +33,8 @@ import { getActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags'; import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
import CrossFilterScopingModal from 'src/dashboard/components/CrossFilterScopingModal/CrossFilterScopingModal'; import CrossFilterScopingModal from 'src/dashboard/components/CrossFilterScopingModal/CrossFilterScopingModal';
import Icons from 'src/components/Icons'; import Icons from 'src/components/Icons';
import ModalTrigger from 'src/components/ModalTrigger';
import ViewQueryModal from 'src/explore/components/controls/ViewQueryModal';
const propTypes = { const propTypes = {
slice: PropTypes.object.isRequired, slice: PropTypes.object.isRequired,
@ -76,6 +78,7 @@ const MENU_KEYS = {
EXPORT_CSV: 'export_csv', EXPORT_CSV: 'export_csv',
RESIZE_LABEL: 'resize_label', RESIZE_LABEL: 'resize_label',
DOWNLOAD_AS_IMAGE: 'download_as_image', DOWNLOAD_AS_IMAGE: 'download_as_image',
VIEW_QUERY: 'view_query',
}; };
const VerticalDotsContainer = styled.div` const VerticalDotsContainer = styled.div`
@ -256,6 +259,21 @@ class SliceHeaderControls extends React.PureComponent {
</Menu.Item> </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 && ( {supersetCanShare && (
<ShareMenuItems <ShareMenuItems
url={getDashboardUrl( url={getDashboardUrl(

View File

@ -334,6 +334,7 @@ export default class Chart extends React.Component {
handleToggleFullSize={handleToggleFullSize} handleToggleFullSize={handleToggleFullSize}
isFullSize={isFullSize} isFullSize={isFullSize}
chartStatus={chart.chartStatus} 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 withToasts from 'src/messageToasts/enhancers/withToasts';
import { useUrlShortener } from 'src/common/hooks/useUrlShortener'; import { useUrlShortener } from 'src/common/hooks/useUrlShortener';
import EmbedCodeButton from './EmbedCodeButton'; import EmbedCodeButton from './EmbedCodeButton';
import ConnectedDisplayQueryButton from './DisplayQueryButton';
import { exportChart, getExploreLongUrl } from '../exploreUtils'; import { exportChart, getExploreLongUrl } from '../exploreUtils';
import ExploreAdditionalActionsMenu from './ExploreAdditionalActionsMenu';
type ActionButtonProps = { type ActionButtonProps = {
icon: React.ReactElement; icon: React.ReactElement;
@ -39,7 +39,7 @@ type ActionButtonProps = {
}; };
type ExploreActionButtonsProps = { type ExploreActionButtonsProps = {
actions: { redirectSQLLab: Function; openPropertiesModal: Function }; actions: { redirectSQLLab: () => void; openPropertiesModal: () => void };
canDownloadCSV: boolean; canDownloadCSV: boolean;
chartStatus: string; chartStatus: string;
latestQueryFormData: {}; latestQueryFormData: {};
@ -90,7 +90,6 @@ const ExploreActionButtons = (props: ExploreActionButtonsProps) => {
canDownloadCSV, canDownloadCSV,
chartStatus, chartStatus,
latestQueryFormData, latestQueryFormData,
queriesResponse,
slice, slice,
addDangerToast, addDangerToast,
} = props; } = props;
@ -178,8 +177,7 @@ const ExploreActionButtons = (props: ExploreActionButtonsProps) => {
/> />
</> </>
)} )}
<ConnectedDisplayQueryButton <ExploreAdditionalActionsMenu
queryResponse={queriesResponse?.[0]}
latestQueryFormData={latestQueryFormData} latestQueryFormData={latestQueryFormData}
chartStatus={chartStatus} chartStatus={chartStatus}
onOpenInEditor={actions.redirectSQLLab} 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 chartAction from 'src/chart/chartAction';
import * as downloadAsImage from 'src/utils/downloadAsImage'; import * as downloadAsImage from 'src/utils/downloadAsImage';
import fetchMock from 'fetch-mock'; import fetchMock from 'fetch-mock';
import ConectedDisplayQueryButton from '.'; import ExploreAdditionalActionsMenu from '.';
const createProps = () => ({ const createProps = () => ({
latestQueryFormData: { latestQueryFormData: {
@ -90,15 +90,15 @@ fetchMock.post(
}, },
); );
test('Shoud render a button', () => { test('Should render a button', () => {
const props = createProps(); const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { useRedux: true }); render(<ExploreAdditionalActionsMenu {...props} />, { useRedux: true });
expect(screen.getByRole('button')).toBeInTheDocument(); expect(screen.getByRole('button')).toBeInTheDocument();
}); });
test('Shoud open a menu', () => { test('Should open a menu', () => {
const props = createProps(); const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true, useRedux: true,
}); });
@ -122,9 +122,9 @@ test('Shoud open a menu', () => {
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
test('Shoud call onOpenPropertiesModal when click on "Edit properties"', () => { test('Should call onOpenPropertiesModal when click on "Edit properties"', () => {
const props = createProps(); const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true, useRedux: true,
}); });
expect(props.onOpenInEditor).toBeCalledTimes(0); expect(props.onOpenInEditor).toBeCalledTimes(0);
@ -133,10 +133,10 @@ test('Shoud call onOpenPropertiesModal when click on "Edit properties"', () => {
expect(props.onOpenPropertiesModal).toBeCalledTimes(1); 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 props = createProps();
const getChartDataRequest = jest.spyOn(chartAction, 'getChartDataRequest'); const getChartDataRequest = jest.spyOn(chartAction, 'getChartDataRequest');
render(<ConectedDisplayQueryButton {...props} />, { render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true, useRedux: true,
}); });
@ -150,9 +150,9 @@ test('Shoud call getChartDataRequest when click on "View query"', async () => {
await waitFor(() => expect(getChartDataRequest).toBeCalledTimes(1)); 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(); const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true, useRedux: true,
}); });
@ -164,10 +164,10 @@ test('Shoud call onOpenInEditor when click on "Run in SQL Lab"', () => {
expect(props.onOpenInEditor).toBeCalledTimes(1); 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 props = createProps();
const spy = jest.spyOn(downloadAsImage, 'default'); const spy = jest.spyOn(downloadAsImage, 'default');
render(<ConectedDisplayQueryButton {...props} />, { render(<ExploreAdditionalActionsMenu {...props} />, {
useRedux: true, useRedux: true,
}); });

View File

@ -16,31 +16,16 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
import React, { useState } from 'react'; import React from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'; import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light'; import { t } from '@superset-ui/core';
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 { Dropdown, Menu } from 'src/common/components'; 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 downloadAsImage from 'src/utils/downloadAsImage';
import Loading from 'src/components/Loading';
import ModalTrigger from 'src/components/ModalTrigger'; import ModalTrigger from 'src/components/ModalTrigger';
import { sliceUpdated } from 'src/explore/actions/exploreActions'; import { sliceUpdated } from 'src/explore/actions/exploreActions';
import { CopyButton } from 'src/explore/components/DataTableControl'; import ViewQueryModal from '../controls/ViewQueryModal';
SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
SyntaxHighlighter.registerLanguage('html', htmlSyntax);
SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
SyntaxHighlighter.registerLanguage('json', jsonSyntax);
const propTypes = { const propTypes = {
onOpenPropertiesModal: PropTypes.func, onOpenPropertiesModal: PropTypes.func,
@ -54,53 +39,12 @@ const MENU_KEYS = {
EDIT_PROPERTIES: 'edit_properties', EDIT_PROPERTIES: 'edit_properties',
RUN_IN_SQL_LAB: 'run_in_sql_lab', RUN_IN_SQL_LAB: 'run_in_sql_lab',
DOWNLOAD_AS_IMAGE: 'download_as_image', DOWNLOAD_AS_IMAGE: 'download_as_image',
VIEW_QUERY: 'view_query',
}; };
const CopyButtonViewQuery = styled(CopyButton)` const ExploreAdditionalActionsMenu = props => {
&& {
margin: 0 0 ${({ theme }) => theme.gridUnit}px;
}
`;
export const DisplayQueryButton = props => {
const { datasource } = props.latestQueryFormData; const { datasource } = props.latestQueryFormData;
const sqlSupported = datasource && datasource.split('__')[1] === 'table';
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 handleMenuClick = ({ key, domEvent }) => { const handleMenuClick = ({ key, domEvent }) => {
const { slice, onOpenInEditor, latestQueryFormData } = props; const { slice, onOpenInEditor, latestQueryFormData } = props;
switch (key) { 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; const { slice } = props;
return ( return (
<Dropdown <Dropdown
@ -164,14 +80,17 @@ export const DisplayQueryButton = props => {
{t('Edit properties')} {t('Edit properties')}
</Menu.Item> </Menu.Item>
)} )}
<Menu.Item> <Menu.Item key={MENU_KEYS.VIEW_QUERY}>
<ModalTrigger <ModalTrigger
triggerNode={ triggerNode={
<span data-test="view-query-menu-item">{t('View query')}</span> <span data-test="view-query-menu-item">{t('View query')}</span>
} }
modalTitle={t('View query')} modalTitle={t('View query')}
beforeOpen={() => beforeOpen('query')} modalBody={
modalBody={renderQueryModalBody()} <ViewQueryModal
latestQueryFormData={props.latestQueryFormData}
/>
}
responsive responsive
/> />
</Menu.Item> </Menu.Item>
@ -198,10 +117,10 @@ export const DisplayQueryButton = props => {
); );
}; };
DisplayQueryButton.propTypes = propTypes; ExploreAdditionalActionsMenu.propTypes = propTypes;
function mapDispatchToProps(dispatch) { function mapDispatchToProps(dispatch) {
return bindActionCreators({ sliceUpdated }, 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;