Skip to content

Commit

Permalink
fix: always pass a string as a value to ace editor (#13563)
Browse files Browse the repository at this point in the history
* always pass a string as a value to ace editor

* fix some syntax
  • Loading branch information
eschutho authored Mar 13, 2021
1 parent 06d6d7f commit 67ffea8
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 33 deletions.
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: () => void;
}) {
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: 4 additions & 0 deletions superset-frontend/src/components/AsyncAceEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ export default function AsyncAceEditor(
mode = inferredMode,
theme = inferredTheme,
tabSize = defaultTabSize,
defaultValue = '',
value = '',
...props
},
ref,
Expand Down Expand Up @@ -150,6 +152,8 @@ export default function AsyncAceEditor(
mode={mode}
theme={theme}
tabSize={tabSize}
defaultValue={defaultValue}
value={value || ''}
{...props}
/>
);
Expand Down

0 comments on commit 67ffea8

Please sign in to comment.