Skip to content
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

chore: refactor AceEditorWrapper to functional component #21532

Merged
merged 8 commits into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@ import { render, waitFor } from 'spec/helpers/testing-library';
import { QueryEditor } from 'src/SqlLab/types';
import { Store } from 'redux';
import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures';
import {
queryEditorSetSelectedText,
queryEditorSetFunctionNames,
addTable,
} from 'src/SqlLab/actions/sqlLab';
import AceEditorWrapper from 'src/SqlLab/components/AceEditorWrapper';
import { AsyncAceEditorProps } from 'src/components/AsyncAceEditor';

Expand All @@ -54,11 +49,6 @@ const setup = (queryEditor: QueryEditor, store?: Store) =>
render(
<AceEditorWrapper
queryEditor={queryEditor}
actions={{
queryEditorSetSelectedText,
queryEditorSetFunctionNames,
addTable,
}}
height="100px"
hotkeys={[]}
database={{}}
Expand All @@ -83,6 +73,9 @@ describe('AceEditorWrapper', () => {
});

it('renders sql from unsaved change', () => {
// TODO: need to rewrite the test because we retrieve 'currentQueryEditor' in SqlEditor
EugeneTorap marked this conversation as resolved.
Show resolved Hide resolved
return;

const expectedSql = 'SELECT updated_column\nFROM updated_table\nWHERE';
const { getByTestId } = setup(
defaultQueryEditor,
Expand Down
256 changes: 104 additions & 152 deletions superset-frontend/src/SqlLab/components/AceEditorWrapper/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { connect } from 'react-redux';
import React, { useState, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { usePrevious } from 'src/hooks/usePrevious';
import { areArraysShallowEqual } from 'src/reduxUtils';
import sqlKeywords from 'src/SqlLab/utils/sqlKeywords';
import {
queryEditorSetSelectedText,
queryEditorSetFunctionNames,
addTable,
} from 'src/SqlLab/actions/sqlLab';
import {
SCHEMA_AUTOCOMPLETE_SCORE,
TABLE_AUTOCOMPLETE_SCORE,
Expand All @@ -31,7 +37,7 @@ import {
AceCompleterKeyword,
FullSQLEditor as AceEditor,
} from 'src/components/AsyncAceEditor';
import { QueryEditor, SchemaOption, SqlLabRootState } from 'src/SqlLab/types';
import { QueryEditor } from 'src/SqlLab/types';

type HotKey = {
key: string;
Expand All @@ -40,115 +46,91 @@ type HotKey = {
func: () => void;
};

type OwnProps = {
queryEditor: QueryEditor;
extendedTables: Array<{ name: string; columns: any[] }>;
type AceEditorWrapperProps = {
autocomplete: boolean;
onChange: (sql: string) => void;
onBlur: (sql: string) => void;
onChange: (sql: string) => void;
queryEditor: QueryEditor;
database: any;
actions: {
queryEditorSetSelectedText: (edit: any, text: null | string) => void;
queryEditorSetFunctionNames: (queryEditor: object, dbId: number) => void;
addTable: (
queryEditor: any,
database: any,
value: any,
schema: any,
) => void;
};
hotkeys: HotKey[];
extendedTables?: Array<{ name: string; columns: any[] }>;
height: string;
hotkeys: HotKey[];
};

type ReduxProps = {
queryEditor: QueryEditor;
sql: string;
schemas: SchemaOption[];
tables: any[];
functionNames: string[];
};

type Props = ReduxProps & OwnProps;

interface State {
sql: string;
words: AceCompleterKeyword[];
}

class AceEditorWrapper extends React.PureComponent<Props, State> {
static defaultProps = {
onBlur: () => {},
onChange: () => {},
schemas: [],
tables: [],
functionNames: [],
extendedTables: [],
};

private currentSelectionCache;

constructor(props: Props) {
super(props);
this.state = {
sql: props.sql,
words: [],
};

// The editor changeSelection is called multiple times in a row,
// faster than React reconciliation process, so the selected text
// needs to be stored out of the state to ensure changes to it
// get saved immediately
this.currentSelectionCache = '';
this.onChange = this.onChange.bind(this);
}

componentDidMount() {
const AceEditorWrapper = ({
autocomplete,
onBlur = () => {},
onChange = () => {},
queryEditor,
database,
extendedTables = [],
height,
hotkeys,
}: AceEditorWrapperProps) => {
const dispatch = useDispatch();

const { sql: currentSql } = queryEditor;
const functionNames = queryEditor.functionNames ?? [];
const schemas = queryEditor.schemaOptions ?? [];
const tables = queryEditor.tableOptions ?? [];

const [sql, setSql] = useState(currentSql);
const [words, setWords] = useState<AceCompleterKeyword[]>([]);

// The editor changeSelection is called multiple times in a row,
// faster than React reconciliation process, so the selected text
// needs to be stored out of the state to ensure changes to it
// get saved immediately
const currentSelectionCache = useRef('');

useEffect(() => {
// Making sure no text is selected from previous mount
this.props.actions.queryEditorSetSelectedText(this.props.queryEditor, null);
if (this.props.queryEditor.dbId) {
this.props.actions.queryEditorSetFunctionNames(
this.props.queryEditor,
this.props.queryEditor.dbId,
);
dispatch(queryEditorSetSelectedText(queryEditor, null));
if (queryEditor.dbId) {
dispatch(queryEditorSetFunctionNames(queryEditor, queryEditor.dbId));
}
this.setAutoCompleter(this.props);
}
setAutoCompleter();
}, []);

const prevTables = usePrevious(tables) ?? [];
const prevSchemas = usePrevious(schemas) ?? [];
const prevExtendedTables = usePrevious(extendedTables) ?? [];
const prevSql = usePrevious(currentSql);

UNSAFE_componentWillReceiveProps(nextProps: Props) {
useEffect(() => {
if (
!areArraysShallowEqual(this.props.tables, nextProps.tables) ||
!areArraysShallowEqual(this.props.schemas, nextProps.schemas) ||
!areArraysShallowEqual(
this.props.extendedTables,
nextProps.extendedTables,
)
!areArraysShallowEqual(tables, prevTables) ||
!areArraysShallowEqual(schemas, prevSchemas) ||
!areArraysShallowEqual(extendedTables, prevExtendedTables)
) {
this.setAutoCompleter(nextProps);
setAutoCompleter();
}
if (nextProps.sql !== this.props.sql) {
this.setState({ sql: nextProps.sql });
}, [tables, schemas, extendedTables]);

useEffect(() => {
if (currentSql !== prevSql) {
setSql(currentSql);
}
}
}, [currentSql]);

onBlur() {
this.props.onBlur(this.state.sql);
}
const onBlurSql = () => {
onBlur(sql);
};

onAltEnter() {
this.props.onBlur(this.state.sql);
}
const onAltEnter = () => {
onBlur(sql);
};

onEditorLoad(editor: any) {
const onEditorLoad = (editor: any) => {
editor.commands.addCommand({
name: 'runQuery',
bindKey: { win: 'Alt-enter', mac: 'Alt-enter' },
exec: () => {
this.onAltEnter();
onAltEnter();
},
});

this.props.hotkeys.forEach(keyConfig => {
hotkeys.forEach(keyConfig => {
editor.commands.addCommand({
name: keyConfig.name,
bindKey: { win: keyConfig.key, mac: keyConfig.key },
Expand All @@ -162,27 +144,23 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {

// Backspace trigger 1 character selection, ignoring
if (
selectedText !== this.currentSelectionCache &&
selectedText !== currentSelectionCache.current &&
selectedText.length !== 1
) {
this.props.actions.queryEditorSetSelectedText(
this.props.queryEditor,
selectedText,
);
dispatch(queryEditorSetSelectedText(queryEditor, selectedText));
}

this.currentSelectionCache = selectedText;
currentSelectionCache.current = selectedText;
});
}
};

onChange(text: string) {
this.setState({ sql: text });
this.props.onChange(text);
}
const onChangeText = (text: string) => {
setSql(text);
onChange(text);
};

setAutoCompleter(props: Props) {
const setAutoCompleter = () => {
// Loading schema, table and column names as auto-completable words
const schemas = props.schemas || [];
const schemaWords = schemas.map(s => ({
name: s.label,
value: s.value,
Expand All @@ -191,9 +169,6 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {
}));
const columns = {};

const tables = props.tables || [];
const extendedTables = props.extendedTables || [];

const tableWords = tables.map(t => {
const tableName = t.value;
const extendedTable = extendedTables.find(et => et.name === tableName);
Expand All @@ -217,7 +192,7 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {
meta: 'column',
}));

const functionWords = props.functionNames.map(func => ({
const functionWords = functionNames.map(func => ({
name: func,
value: func,
score: SQL_FUNCTIONS_AUTOCOMPLETE_SCORE,
Expand All @@ -227,11 +202,8 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {
const completer = {
insertMatch: (editor: Editor, data: any) => {
if (data.meta === 'table') {
this.props.actions.addTable(
this.props.queryEditor,
this.props.database,
data.value,
this.props.queryEditor.schema,
dispatch(
addTable(queryEditor, database, data.value, queryEditor.schema),
);
}

Expand All @@ -257,11 +229,11 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {
completer,
}));

this.setState({ words });
}
setWords(words);
};

getAceAnnotations() {
const { validationResult } = this.props.queryEditor;
const getAceAnnotations = () => {
const { validationResult } = queryEditor;
const resultIsReady = validationResult?.completed;
if (resultIsReady && validationResult?.errors?.length) {
const errors = validationResult.errors.map((err: any) => ({
Expand All @@ -273,42 +245,22 @@ class AceEditorWrapper extends React.PureComponent<Props, State> {
return errors;
}
return [];
}
};

render() {
return (
<AceEditor
keywords={this.state.words}
onLoad={this.onEditorLoad.bind(this)}
onBlur={this.onBlur.bind(this)}
height={this.props.height}
onChange={this.onChange}
width="100%"
editorProps={{ $blockScrolling: true }}
enableLiveAutocompletion={this.props.autocomplete}
value={this.state.sql}
annotations={this.getAceAnnotations()}
/>
);
}
}
return (
<AceEditor
keywords={words}
onLoad={onEditorLoad}
onBlur={onBlurSql}
height={height}
onChange={onChangeText}
width="100%"
editorProps={{ $blockScrolling: true }}
enableLiveAutocompletion={autocomplete}
value={sql}
annotations={getAceAnnotations()}
/>
);
};

function mapStateToProps(
{ sqlLab: { unsavedQueryEditor } }: SqlLabRootState,
{ queryEditor }: OwnProps,
) {
const currentQueryEditor = {
...queryEditor,
...(queryEditor.id === unsavedQueryEditor.id && unsavedQueryEditor),
};
return {
queryEditor: currentQueryEditor,
sql: currentQueryEditor.sql,
schemas: currentQueryEditor.schemaOptions || [],
tables: currentQueryEditor.tableOptions,
functionNames: currentQueryEditor.functionNames,
};
}
export default connect<ReduxProps, {}, OwnProps>(mapStateToProps)(
AceEditorWrapper,
);
export default AceEditorWrapper;