Skip to content

fix: always pass a string as a value to ace editor #13563

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 13, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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,57 @@
/**
* 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, { ReactNode } from 'react';
import {
render,
fireEvent,
getByText,
waitFor,
} from 'spec/helpers/testing-library';
import brace from 'brace';
import { ThemeProvider, supersetTheme } from '@superset-ui/core';

import TemplateParamsEditor from 'src/SqlLab/components/TemplateParamsEditor';

const ThemeWrapper = ({ children }: { children: ReactNode }) => (
<ThemeProvider theme={supersetTheme}>{children}</ThemeProvider>
);

describe('TemplateParamsEditor', () => {
it('should render with a title', () => {
const { container } = render(
<TemplateParamsEditor code="FOO" language="json" onChange={() => {}} />,
{ wrapper: ThemeWrapper },
);
expect(container.querySelector('div[role="button"]')).toBeInTheDocument();
});

it('should open a modal with the ace editor', async () => {
const { container, baseElement } = render(
<TemplateParamsEditor code="FOO" language="json" onChange={() => {}} />,
{ wrapper: ThemeWrapper },
);
fireEvent.click(getByText(container, 'Parameters'));
const spy = jest.spyOn(brace, 'acequire');
spy.mockReturnValue({ setCompleters: () => 'foo' });
await waitFor(() => {
expect(baseElement.querySelector('#brace-editor')).toBeInTheDocument();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* under the License.
*/
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import Badge from 'src/components/Badge';
import { t, styled } from '@superset-ui/core';
import { InfoTooltipWithTrigger } from '@superset-ui/chart-controls';
Expand All @@ -26,34 +25,32 @@ import { debounce } from 'lodash';
import ModalTrigger from 'src/components/ModalTrigger';
import { ConfigEditor } from 'src/components/AsyncAceEditor';
import { FAST_DEBOUNCE } from 'src/constants';

const propTypes = {
onChange: PropTypes.func,
code: PropTypes.string,
language: PropTypes.oneOf(['yaml', 'json']),
};

const defaultProps = {
onChange: () => {},
code: '{}',
};
import { Tooltip } from 'src/common/components/Tooltip';

const StyledConfigEditor = styled(ConfigEditor)`
&.ace_editor {
border: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
}
`;

function TemplateParamsEditor({ code, language, onChange }) {
const [parsedJSON, setParsedJSON] = useState();
function TemplateParamsEditor({
code = '{}',
language,
onChange = () => {},
}: {
code: string;
language: 'yaml' | 'json';
onChange: (...args: any) => any;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about this?

Suggested change
onChange: (...args: any) => any;
onChange: () => void;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we are convert SqlEditor.jsx to the typescript, we can add function parameter type again.

<TemplateParamsEditor
language="json"
onChange={params => {
this.props.actions.queryEditorSetTemplateParams(qe, params);
}}
code={qe.templateParams}
/>

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be getting to it soon, and then, yes we'll be able to manage types of props better, ya!

}) {
const [parsedJSON, setParsedJSON] = useState({});
const [isValid, setIsValid] = useState(true);

useEffect(() => {
try {
setParsedJSON(JSON.parse(code));
setIsValid(true);
} catch {
setParsedJSON({});
setParsedJSON({} as any);
setIsValid(false);
}
}, [code]);
Expand Down Expand Up @@ -96,25 +93,29 @@ function TemplateParamsEditor({ code, language, onChange }) {
<ModalTrigger
modalTitle={t('Template parameters')}
triggerNode={
<div tooltip={t('Edit template parameters')} buttonSize="small">
{`${t('Parameters')} `}
<Badge count={paramCount} />
{!isValid && (
<InfoTooltipWithTrigger
icon="exclamation-triangle"
bsStyle="danger"
tooltip={t('Invalid JSON')}
label="invalid-json"
/>
)}
</div>
<Tooltip
id="parameters-tooltip"
placement="top"
title={t('Edit template parameters')}
trigger={['hover']}
>
<div role="button">
{`${t('Parameters')} `}
<Badge count={paramCount} />
{!isValid && (
<InfoTooltipWithTrigger
icon="exclamation-triangle"
bsStyle="danger"
tooltip={t('Invalid JSON')}
label="invalid-json"
/>
)}
</div>
</Tooltip>
}
modalBody={modalBody}
/>
);
}

TemplateParamsEditor.propTypes = propTypes;
TemplateParamsEditor.defaultProps = defaultProps;

export default TemplateParamsEditor;
6 changes: 3 additions & 3 deletions superset-frontend/src/SqlLab/reducers/getInitialState.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ export default function getInitialState({
id: id.toString(),
loaded: true,
title: activeTab.label,
sql: activeTab.sql,
selectedText: null,
sql: activeTab.sql || undefined,
selectedText: undefined,
latestQueryId: activeTab.latest_query
? activeTab.latest_query.id
: null,
autorun: activeTab.autorun,
templateParams: activeTab.template_params,
templateParams: activeTab.template_params || undefined,
dbId: activeTab.database_id,
functionNames: [],
schema: activeTab.schema,
Expand Down
11 changes: 11 additions & 0 deletions superset-frontend/src/SqlLab/reducers/getInitialState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,19 @@ const apiData = {
username: 'some name',
},
};
const apiDataWithTabState = {
...apiData,
tab_state_ids: [{ id: 1 }],
active_tab: { id: 1, table_schemas: [] },
};
describe('getInitialState', () => {
it('should output the user that is passed in', () => {
expect(getInitialState(apiData).sqlLab.user.userId).toEqual(1);
});
it('should return undefined instead of null for templateParams', () => {
expect(
getInitialState(apiDataWithTabState).sqlLab.queryEditors[0]
.templateParams,
).toBeUndefined();
});
});
4 changes: 3 additions & 1 deletion superset-frontend/src/components/AsyncAceEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export default function AsyncAceEditor(
mode = inferredMode,
theme = inferredTheme,
tabSize = defaultTabSize,
defaultValue = '',
...props
},
ref,
Expand Down Expand Up @@ -150,7 +151,8 @@ export default function AsyncAceEditor(
mode={mode}
theme={theme}
tabSize={tabSize}
{...props}
defaultValue={defaultValue}
{...{ ...props, value: props.value || '' }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The syntax here looks alien. 😄

Why not:

Suggested change
{...{ ...props, value: props.value || '' }}
{...props}
value={props.value || '' }

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ha, yeah, that was my first implementation, but often people like to see the "rest" props at the end, and so I anticipated someone changing this order in the context of "cleanup". I think I found a way around this.. lmk what you think.

/>
);
},
Expand Down