import React, { useState, useCallback } from "react"; import { Query, Builder, Utils as QbUtils, JsonSwitchGroup, Config, ImmutableTree, BuilderProps } from "react-awesome-query-builder"; import "../../css/styles.scss"; import getConfig from "./config"; const config: Config = getConfig(); const preStyle = { backgroundColor: "darkgrey", margin: "10px", padding: "10px" }; const preErrorStyle = { backgroundColor: "lightpink", margin: "10px", padding: "10px" }; const emptyJsonTree: JsonSwitchGroup = { id: QbUtils.uuid(), type: "switch_group", }; const emptyTree: ImmutableTree = QbUtils.checkTree(QbUtils.loadTree(emptyJsonTree), config); const Demo: React.FC = () => { const [state, setState] = useState({ tree: emptyTree, config: config, spelStr: "", spelErrors: [] as string[], }); const onChange = useCallback((tree: ImmutableTree, config: Config) => { setState(prevState => ({ ...prevState, tree, config })); }, []); const renderBuilder = useCallback((props: BuilderProps) => (
), []); const onChangeSpelStr = (e: React.ChangeEvent) => { const spelStr = e.target.value; setState({ ...state, spelStr }); }; const importFromSpel = () => { const [tree, spelErrors] = QbUtils.loadFromSpel(state.spelStr, state.config); setState({ ...state, tree: tree ? QbUtils.checkTree(tree, state.config) : state.tree, spelErrors }); }; const renderQueryBuilder = () => ( ); const renderSpelOutput = () => (
Output SpEL:
        {QbUtils.spelFormat(state.tree, state.config)}
      
Values:
        {JSON.stringify(QbUtils.getSwitchValues(state.tree), undefined, 2)}
      
); const renderSpelInput = () => (
Input SpEL:
{ state.spelErrors.length > 0 &&
            {JSON.stringify(state.spelErrors, undefined, 2)}
          
}
); return (
{renderSpelInput()} {renderQueryBuilder()} {renderSpelOutput()}
); }; export default Demo;