import React from 'react'; import { dataqueryService } from '@/_services'; import { toast } from 'react-hot-toast'; import ReactTooltip from 'react-tooltip'; import { allSources } from './QueryEditors'; import { Transformation } from './Transformation'; import { previewQuery } from '@/_helpers/appUtils'; import { EventManager } from '../Inspector/EventManager'; import { CodeHinter } from '../CodeBuilder/CodeHinter'; import { DataSourceTypes } from '../DataSourceManager/SourceComponents'; import RunjsIcon from '../Icons/runjs.svg'; import Preview from './Preview'; import DataSourceLister from './DataSourceLister'; import { allSvgs } from '@tooljet/plugins/client'; // import { Confirm } from '../Viewer/Confirm'; import _ from 'lodash'; const queryNameRegex = new RegExp('^[A-Za-z0-9_-]*$'); const staticDataSources = [ { kind: 'restapi', id: 'null', name: 'REST API' }, { kind: 'runjs', id: 'runjs', name: 'Run JavaScript code' }, ]; let QueryManager = class QueryManager extends React.Component { constructor(props) { super(props); this.state = { options: {}, selectedQuery: null, selectedDataSource: null, dataSourceMeta: {}, dataQueries: [], theme: {}, isSourceSelected: false, isFieldsChanged: false, paneHeightChanged: false, showSaveConfirmation: false, restArrayValuesChanged: false, nextProps: null, }; this.previewPanelRef = React.createRef(); } setStateFromProps = (props) => { const selectedQuery = props.selectedQuery; const dataSourceId = selectedQuery?.data_source_id; const source = props.dataSources.find((datasource) => datasource.id === dataSourceId); let dataSourceMeta = DataSourceTypes.find((source) => source.kind === selectedQuery?.kind); const paneHeightChanged = this.state.queryPaneHeight !== props.queryPaneHeight; const dataQueries = props.dataQueries?.length ? props.dataQueries : this.state.dataQueries; const queryPaneDragged = this.state.isQueryPaneDragging !== props.isQueryPaneDragging; this.setState( { appId: props.appId, dataSources: props.dataSources, dataQueries: dataQueries, mode: props.mode, currentTab: 1, addingQuery: props.addingQuery, editingQuery: props.editingQuery, queryPaneHeight: props.queryPaneHeight, isQueryPaneDragging: props.isQueryPaneDragging, currentState: props.currentState, selectedSource: source, dataSourceMeta, paneHeightChanged, isSourceSelected: paneHeightChanged || queryPaneDragged ? this.state.isSourceSelected : props.isSourceSelected, selectedDataSource: paneHeightChanged || queryPaneDragged ? this.state.selectedDataSource : props.selectedDataSource, theme: { scheme: 'bright', author: 'chris kempson (http://chriskempson.com)', base00: props.darkMode ? '#272822' : '#000000', base01: '#303030', base02: '#505050', base03: '#b0b0b0', base04: '#d0d0d0', base05: '#e0e0e0', base06: '#f5f5f5', base07: '#ffffff', base08: '#fb0120', base09: '#fc6d24', base0A: '#fda331', base0B: '#a1c659', base0C: '#76c7b7', base0D: '#6fb3d2', base0E: '#d381c3', base0F: '#be643c', }, }, () => { if (this.props.mode === 'edit') { let source = props.dataSources.find((datasource) => datasource.id === selectedQuery.data_source_id); if (selectedQuery.kind === 'restapi') { if (!selectedQuery.data_source_id) { source = { kind: 'restapi', id: 'null', name: 'REST API' }; } } if (selectedQuery.kind === 'runjs') { if (!selectedQuery.data_source_id) { source = { kind: 'runjs', id: 'runjs', name: 'Run JavaScript code' }; } } this.setState({ options: paneHeightChanged || this.state.selectedQuery?.id === selectedQuery?.id ? this.state.options : selectedQuery.options, selectedDataSource: source, selectedQuery, queryName: selectedQuery.name, }); } } ); }; componentWillReceiveProps(nextProps) { // const themeModeChanged = this.props.darkMode !== nextProps.darkMode; // if (!nextProps.isQueryPaneDragging && !this.state.paneHeightChanged && !themeModeChanged) { // if (this.props.mode === 'create' && this.state.isFieldsChanged) { // this.setState({ showSaveConfirmation: true, nextProps }); // return; // } else if (this.props.mode === 'edit') { // if (this.state.selectedQuery) { // const isQueryChanged = !_.isEqual( // this.removeRestKey(this.state.options), // this.removeRestKey(this.state.selectedQuery.options) // ); // if (this.state.isFieldsChanged && isQueryChanged) { // this.setState({ showSaveConfirmation: true, nextProps }); // return; // } else if ( // !isQueryChanged && // this.state.selectedQuery.kind === 'restapi' && // this.state.restArrayValuesChanged // ) { // this.setState({ showSaveConfirmation: true, nextProps }); // return; // } // } // } // } this.setStateFromProps(nextProps); } removeRestKey = (options) => { delete options.arrayValuesChanged; return options; }; componentDidMount() { this.setStateFromProps(this.props); } handleBackButton = () => { this.setState({ isSourceSelected: true, }); }; changeDataSource = (sourceId) => { const source = [...this.state.dataSources, ...staticDataSources].find((datasource) => datasource.id === sourceId); const isSchemaUnavailable = ['restapi', 'stripe', 'runjs'].includes(source.kind); const schemaUnavailableOptions = { restapi: { method: 'get', url: null, url_params: [], headers: [], body: [], }, stripe: {}, runjs: {}, }; this.setState({ selectedDataSource: source, selectedSource: source, queryName: this.computeQueryName(source.kind), ...(isSchemaUnavailable && { options: schemaUnavailableOptions[source.kind], }), }); }; switchCurrentTab = (tab) => { this.setState({ currentTab: tab, }); }; validateQueryName = () => { const { queryName, dataQueries, mode, selectedQuery } = this.state; if (mode === 'create') { return dataQueries.find((query) => query.name === queryName) === undefined && queryNameRegex.test(queryName); } const existingQuery = dataQueries.find((query) => query.name === queryName); if (existingQuery) { return existingQuery.id === selectedQuery.id && queryNameRegex.test(queryName); } return queryNameRegex.test(queryName); }; computeQueryName = (kind) => { const { dataQueries } = this.state; const currentQueriesForKind = dataQueries.filter((query) => query.kind === kind); let found = false; let newName = ''; let currentNumber = currentQueriesForKind.length + 1; while (!found) { newName = `${kind}${currentNumber}`; if (dataQueries.find((query) => query.name === newName) === undefined) { found = true; } currentNumber += 1; } return newName; }; createOrUpdateDataQuery = () => { const { appId, options, selectedDataSource, mode, queryName } = this.state; const appVersionId = this.props.editingVersionId; const kind = selectedDataSource.kind; const dataSourceId = selectedDataSource.id === 'null' ? null : selectedDataSource.id; const isQueryNameValid = this.validateQueryName(); if (!isQueryNameValid) { toast.error('Invalid query name. Should be unique and only include letters, numbers and underscore.'); return; } if (mode === 'edit') { this.setState({ isUpdating: true }); dataqueryService .update(this.state.selectedQuery.id, queryName, options) .then(() => { toast.success('Query Updated'); this.setState({ isUpdating: false, isFieldsChanged: false, restArrayValuesChanged: false }); this.props.dataQueriesChanged(); }) .catch(({ error }) => { this.setState({ isUpdating: false, isFieldsChanged: false, restArrayValuesChanged: false }); toast.error(error); }); } else { this.setState({ isCreating: true }); dataqueryService .create(appId, appVersionId, queryName, kind, options, dataSourceId) .then(() => { toast.success('Query Added'); this.setState({ isCreating: false, isFieldsChanged: false, restArrayValuesChanged: false }); this.props.dataQueriesChanged(); }) .catch(({ error }) => { this.setState({ isCreating: false, isFieldsChanged: false, restArrayValuesChanged: false }); toast.error(error); }); } }; optionchanged = (option, value) => { this.setState({ options: { ...this.state.options, [option]: value }, isFieldsChanged: true }); }; optionsChanged = (newOptions) => { this.setState({ options: newOptions, isFieldsChanged: true, restArrayValuesChanged: newOptions.arrayValuesChanged, }); }; toggleOption = (option) => { const currentValue = this.state.options[option] ? this.state.options[option] : false; this.optionchanged(option, !currentValue); }; // Here we have mocked data query in format of a component to be usable by event manager // TODO: Refactor EventManager to be generic mockDataQueryAsComponent = () => { const dataQueryEvents = this.state.options?.events || []; return { component: { component: { definition: { events: dataQueryEvents } } }, componentMeta: { events: { onDataQuerySuccess: { displayName: 'Query Success' }, onDataQueryFailure: { displayName: 'Query Failure' }, }, }, }; }; eventsChanged = (events) => { this.optionchanged('events', events); }; render() { const { dataSources, selectedDataSource, mode, options, currentTab, isUpdating, isCreating, addingQuery, editingQuery, selectedQuery, currentState, queryName, previewLoading, queryPreviewData, dataSourceMeta, } = this.state; let ElementToRender = ''; if (selectedDataSource) { const sourcecomponentName = selectedDataSource.kind.charAt(0).toUpperCase() + selectedDataSource.kind.slice(1); ElementToRender = allSources[sourcecomponentName]; } let buttonText = mode === 'edit' ? 'Save' : 'Create'; const buttonDisabled = isUpdating || isCreating; const mockDataQueryComponent = this.mockDataQueryAsComponent(); const Icon = allSvgs[this?.state?.selectedDataSource?.kind]; return (
{/* this.createOrUpdateDataQuery()} onCancel={() => { this.setState({ showSaveConfirmation: false, isFieldsChanged: false }); this.setStateFromProps(this.state.nextProps); }} queryConfirmationData={this.state.queryConfirmationData} /> */}
{(addingQuery || editingQuery) && selectedDataSource && ( )}
{(addingQuery || editingQuery) && selectedDataSource && (
this.setState({ queryName: e.target.value })} className="form-control-plaintext form-control-plaintext-sm mt-1" value={queryName} autoFocus={false} />
)}
{selectedDataSource && (addingQuery || editingQuery) && ( )} {selectedDataSource && (addingQuery || editingQuery) && ( )}
{(addingQuery || editingQuery) && (
{currentTab === 1 && (
{dataSources && mode === 'create' && (
{this.state.selectedDataSource !== null && (

{ this.setState({ isSourceSelected: false, selectedDataSource: null, }); }} style={{ marginTop: '-7px' }} >

)} {!this.state.isSourceSelected && }{' '} {this?.state?.selectedDataSource?.kind && (
{this.state?.selectedDataSource?.kind === 'runjs' ? ( ) : ( Icon && )}

{' '} {this.state?.selectedDataSource?.kind && this.state.selectedDataSource.kind}

{' '}
)}
{!this.state.isSourceSelected && ( )}
)} {selectedDataSource && (
{!dataSourceMeta?.disableTransformations && (
)}
)}
)} {currentTab === 2 && (
this.toggleOption('runOnPageLoad')} checked={this.state.options.runOnPageLoad} /> Run this query on page load?
this.toggleOption('requestConfirmation')} checked={this.state.options.requestConfirmation} /> Request confirmation before running query?
this.toggleOption('showSuccessNotification')} checked={this.state.options.showSuccessNotification} /> Show notification on success?
{this.state.options.showSuccessNotification && (
this.optionchanged('successMessage', value)} placeholder="Query ran successfully" />
this.optionchanged('notificationDuration', e.target.value)} placeholder={5} className="form-control" value={this.state.options.notificationDuration} />
)}
Events
)}
)}
); } }; QueryManager = React.memo(QueryManager); export { QueryManager };