Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: saved query preview modal #11135

Merged
merged 4 commits into from
Oct 5, 2020
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/**
* 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 from 'react';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import { styledMount as mount } from 'spec/helpers/theming';
import SavedQueryPreviewModal from 'src/views/CRUD/data/savedquery/SavedQueryPreviewModal';
import Button from 'src/components/Button';
import Modal from 'src/common/components/Modal';
import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint';
import { act } from 'react-dom/test-utils';

// store needed for withToasts(DatabaseList)
const mockStore = configureStore([thunk]);
const store = mockStore({});

const mockqueries = [...new Array(3)].map((_, i) => ({
created_by: {
id: i,
first_name: `user`,
last_name: `${i}`,
},
created_on: `${i}-2020`,
database: {
database_name: `db ${i}`,
id: i,
},
changed_on_delta_humanized: '1 day ago',
db_id: i,
description: `SQL for ${i}`,
id: i,
label: `query ${i}`,
schema: 'public',
sql: `SELECT ${i} FROM table`,
sql_tables: [
{
catalog: null,
schema: null,
table: `${i}`,
},
],
}));

const mockedProps = {
fetchData: jest.fn(() => {}),
openInSqlLab: jest.fn(() => {}),
onHide: () => {},
queries: mockqueries,
savedQuery: mockqueries[1],
show: true,
};

const FETCH_SAVED_QUERY_ENDPOINT = 'glob:*/api/v1/saved_query/*';
const SAVED_QUERY_PAYLOAD = { result: mockqueries[1] };

fetchMock.get(FETCH_SAVED_QUERY_ENDPOINT, SAVED_QUERY_PAYLOAD);

async function mountAndWait(props = mockedProps) {
const mounted = mount(<SavedQueryPreviewModal {...props} />, {
context: { store },
});
await waitForComponentToPaint(mounted);

return mounted;
}

describe('SavedQueryPreviewModal', () => {
let wrapper;

beforeAll(async () => {
wrapper = await mountAndWait();
});

it('renders', () => {
expect(wrapper.find(SavedQueryPreviewModal)).toExist();
});

it('renders a Modal', () => {
expect(wrapper.find(Modal)).toExist();
});

it('renders sql from saved query', () => {
expect(wrapper.find('pre').text()).toEqual('SELECT 1 FROM table');
});

it('renders buttons with correct text', () => {
expect(wrapper.find(Button).contains('Previous')).toBe(true);
expect(wrapper.find(Button).contains('Next')).toBe(true);
expect(wrapper.find(Button).contains('Open in SQL Lab')).toBe(true);
});

it('handle next save query', () => {
const button = wrapper.find('button[data-test="next-saved-query"]');
expect(button.props().disabled).toBe(false);
act(() => {
button.props().onClick(false);
});
expect(mockedProps.fetchData).toHaveBeenCalled();
expect(mockedProps.fetchData.mock.calls[0][0]).toEqual(2);
});

it('handle previous save query', () => {
const button = wrapper
.find('[data-test="previous-saved-query"]')
.find(Button);
expect(button.props().disabled).toBe(false);
act(() => {
button.props().onClick(true);
});
wrapper.update();
expect(mockedProps.fetchData).toHaveBeenCalled();
expect(mockedProps.fetchData.mock.calls[0][0]).toEqual(2);
});

it('handle open in sql lab', async () => {
act(() => {
wrapper.find('[data-test="open-in-sql-lab"]').first().props().onClick();
});
expect(mockedProps.openInSqlLab).toHaveBeenCalled();
expect(mockedProps.openInSqlLab.mock.calls[0][0]).toEqual(1);
});
});
39 changes: 23 additions & 16 deletions superset-frontend/src/common/components/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* under the License.
*/
import React from 'react';
import { isNil } from 'lodash';
import { styled, t } from '@superset-ui/core';
import { Modal as BaseModal } from 'src/common/components';
import Button from 'src/components/Button';
Expand All @@ -26,13 +27,14 @@ interface ModalProps {
children: React.ReactNode;
disablePrimaryButton?: boolean;
onHide: () => void;
onHandledPrimaryAction: () => void;
primaryButtonName: string;
onHandledPrimaryAction?: () => void;
primaryButtonName?: string;
primaryButtonType?: 'primary' | 'danger';
show: boolean;
title: React.ReactNode;
width?: string;
centered?: boolean;
footer?: React.ReactNode;
}

const StyledModal = styled(BaseModal)`
Expand Down Expand Up @@ -96,8 +98,26 @@ export default function Modal({
title,
width,
centered,
footer,
...rest
}: ModalProps) {
const modalFooter = isNil(footer)
? [
<Button key="back" onClick={onHide} cta>
{t('Cancel')}
</Button>,
<Button
key="submit"
buttonStyle={primaryButtonType}
disabled={disablePrimaryButton}
onClick={onHandledPrimaryAction}
cta
>
{primaryButtonName}
</Button>,
]
: footer;

return (
<StyledModal
centered={!!centered}
Expand All @@ -111,20 +131,7 @@ export default function Modal({
×
</span>
}
footer={[
<Button key="back" onClick={onHide} cta>
{t('Cancel')}
</Button>,
<Button
key="submit"
buttonStyle={primaryButtonType}
disabled={disablePrimaryButton}
onClick={onHandledPrimaryAction}
cta
>
{primaryButtonName}
</Button>,
]}
footer={modalFooter}
{...rest}
>
{children}
Expand Down
3 changes: 3 additions & 0 deletions superset-frontend/src/components/ListView/ListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ export interface ListViewProps<T extends object = any> {
renderCard?: (row: T & { loading: boolean }) => React.ReactNode;
cardSortSelectOptions?: Array<CardSortSelectOption>;
defaultViewMode?: ViewModeType;
highlightRowId?: number;
}

function ListView<T extends object = any>({
Expand All @@ -221,6 +222,7 @@ function ListView<T extends object = any>({
renderCard,
cardSortSelectOptions,
defaultViewMode = 'card',
highlightRowId,
}: ListViewProps<T>) {
const {
getTableProps,
Expand Down Expand Up @@ -350,6 +352,7 @@ function ListView<T extends object = any>({
rows={rows}
columns={columns}
loading={loading}
highlightRowId={highlightRowId}
/>
)}
{!loading && rows.length === 0 && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ interface TableCollectionProps {
rows: TableInstance['rows'];
columns: TableInstance['column'][];
loading: boolean;
highlightRowId?: number;
}

const Table = styled.table`
Expand Down Expand Up @@ -199,6 +200,7 @@ export default function TableCollection({
columns,
rows,
loading,
highlightRowId,
}: TableCollectionProps) {
return (
<Table {...getTableProps()} className="table table-hover">
Expand Down Expand Up @@ -262,7 +264,9 @@ export default function TableCollection({
<tr
{...row.getRowProps()}
className={cx('table-row', {
'table-row-selected': row.isSelected,
'table-row-selected':
// @ts-ignore
row.isSelected || row.original.id === highlightRowId,
})}
>
{row.cells.map(cell => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import DeleteModal from 'src/components/DeleteModal';
import ActionsBar, { ActionProps } from 'src/components/ListView/ActionsBar';
import { IconName } from 'src/components/Icon';
import { commonMenuData } from 'src/views/CRUD/data/common';
import SavedQueryPreviewModal from './SavedQueryPreviewModal';

const PAGE_SIZE = 25;

Expand All @@ -48,8 +49,17 @@ interface SavedQueryListProps {
}

type SavedQueryObject = {
database: {
database_name: string;
id: number;
};
db_id: number;
description?: string;
id: number;
label: string;
schema: string;
sql: string;
sql_tables: Array<{ catalog?: string; schema: string; table: string }>;
};

const StyledTableLabel = styled.div`
Expand Down Expand Up @@ -85,11 +95,14 @@ function SavedQueryList({
t('saved_queries'),
addDangerToast,
);

const [
queryCurrentlyDeleting,
setQueryCurrentlyDeleting,
] = useState<SavedQueryObject | null>(null);
const [
savedQueryCurrentlyPreviewing,
setSavedQueryCurrentlyPreviewing,
] = useState<SavedQueryObject | null>(null);

const canCreate = hasPerm('can_add');
const canEdit = hasPerm('can_edit');
Expand All @@ -99,6 +112,21 @@ function SavedQueryList({
window.open(`${window.location.origin}/superset/sqllab?new=true`);
};

const handleSavedQueryPreview = (id: number) => {
SupersetClient.get({
endpoint: `/api/v1/saved_query/${id}`,
}).then(
({ json = {} }) => {
setSavedQueryCurrentlyPreviewing({ ...json.result });
},
createErrorHandler(errMsg =>
addDangerToast(
t('There was an issue previewing the selected query %s', errMsg),
),
),
);
};

const menuData: SubMenuProps = {
activeChild: 'Saved Queries',
...commonMenuData,
Expand Down Expand Up @@ -293,7 +321,9 @@ function SavedQueryList({
},
{
Cell: ({ row: { original } }: any) => {
const handlePreview = () => {}; // openQueryPreviewModal(original); // TODO: open preview modal
const handlePreview = () => {
handleSavedQueryPreview(original.id);
};
const handleEdit = () => {
openInSqlLab(original.id);
};
Expand Down Expand Up @@ -410,6 +440,16 @@ function SavedQueryList({
title={t('Delete Query?')}
/>
)}
{savedQueryCurrentlyPreviewing && (
<SavedQueryPreviewModal
fetchData={handleSavedQueryPreview}
onHide={() => setSavedQueryCurrentlyPreviewing(null)}
savedQuery={savedQueryCurrentlyPreviewing}
queries={queries}
openInSqlLab={openInSqlLab}
show
/>
)}
<ConfirmStatusChange
title={t('Please confirm')}
description={t('Are you sure you want to delete the selected queries?')}
Expand Down Expand Up @@ -441,6 +481,7 @@ function SavedQueryList({
bulkActions={bulkActions}
bulkSelectEnabled={bulkSelectEnabled}
disableBulkSelect={toggleBulkSelect}
highlightRowId={savedQueryCurrentlyPreviewing?.id}
/>
);
}}
Expand Down
Loading