EditNode.jsx 8.19 KB
Newer Older
DarkForst's avatar
DarkForst committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
import React, {useState, useRef, useEffect} from 'react';
import classname from 'classnames'
import {message} from 'antd'
import {createNode, checkSymbol, checkKeycode} from './createNode'
import RuleInfo from './RuleInfo';
import style from './index.less'

const attrList = [
  'properties_realtime', // 实时属性
  'properties_analysis', // 计量属性
  'event', // 事件
  'attr',
]

const EditNode = (props) => {
  const {onEdit, expression, attrInfo, symbolInfo, oStyle,
    clearSymbol, clearAttr, isEdit, addDevice, deleteDevice
  } = props;
  const inputParent = useRef()
  const [extra, setExtra] = useState({})
  const [focusIndex, setFocusIndex] = useState()

  /* 自动获取节点 */
  const autoFocus = (keyIndex, direction) => {
    // console.log('next focus')
    const inputDom = inputParent?.current?.querySelectorAll('input');
    if (!inputDom) return;
    const target = direction ? keyIndex + 1 : keyIndex - 1;
    if (target > inputDom.length) return;
    if(inputDom[target]) inputDom[target].focus()
  }
  /* 添加Node */
  const addNode = (keyIndex, type = 'number', value) => {
    // console.log('addNode')
    let nodeConfig = {type}
    if (type === 'symbol') {nodeConfig.operator = value}
    if (type === 'number') {nodeConfig.value = value}
    if (attrList.includes(type)){
      nodeConfig = {...nodeConfig, ...value}
    }
    const newNode = createNode(nodeConfig)
    const newFuncNode = [...expression]
    newFuncNode.splice(keyIndex, 0, newNode);
    onEdit(newFuncNode)
  }
  /* 键盘输入事件 */
  const inputChange = (event, keyIndex) => {
    const valueCode = event.target.value.charCodeAt(0);
    if (valueCode >= 255) return false;
  };
  /* 失去焦点事件 */
  const finishAdd = (keyIndex) => {
    // console.log('onBLUR', keyIndex)
    setExtra({})
    if (extra.value) {
      const asyncStep = async () => {
        await addNode(keyIndex, 'number', extra.value)
        await autoFocus(keyIndex, true)
      }
      asyncStep().then()

    }
  }
  /* 监听回车删除事件 */
  const keydownAction = (event, keyIndex) => {
    const keyCode = window.event ? event.keyCode : event.which || null
    // console.log(keyCode, 'keyCode')
    // console.log(event.shiftKey, String.fromCharCode(keyCode))
    if (String.fromCharCode(keyCode) === 'å'){
      message.error('请切换英文输入法')
      return;
    }
    const extraValue = extra?.value || '';
    /* 删除事件 */
    if (keyCode === 8) {
      /* 如果有输入内容则删除 */
      if (extra?.keyIndex === keyIndex && extra.value) {
        const newExtra = {...extra}
        const extraValue = newExtra.value
        newExtra.value = extraValue.substring(0, extraValue.length -1)
        setExtra(newExtra)
      }else {
        /* 删除前一节点 */
        if (keyIndex === 0) return;
        const newFuncNode = [...expression];
        // console.log(newFuncNode[keyIndex -1])
        const deleteNode = newFuncNode[keyIndex -1];
        if (attrList.includes(deleteNode.type)){
          // console.log('delete attr')
          deleteDevice && deleteDevice(deleteNode.deviceId)
        }
        newFuncNode.splice(keyIndex - 1, 1);
        onEdit(newFuncNode)
        autoFocus(keyIndex, false)
      }
    }
    /* 回车事件 */
    if (keyCode === 13) {
      const asyncStep = async () => {
        await finishAdd(keyIndex);
        await autoFocus(keyIndex, true)
      }
      asyncStep().then()
    }
    /* 前进事件 */
    if (keyCode === 39 && !extra.value && !event.keyCode) {
      // console.log('---->')
      const inputDom = inputParent.current.querySelectorAll('input');
      const target =  keyIndex + 1;
      if (target > inputDom.length) return;
      if(inputDom[target]) inputDom[target].focus()
    }
    /* 后退事件 */
    if (keyCode === 37 && !extra.value && !event.keyCode) {
      // console.log('<----')
      const inputDom = inputParent.current.querySelectorAll('input');
      const target =  keyIndex - 1;
      if (target < 0) return;
      if(inputDom[target]) inputDom[target].focus()
    }
    /* 数字 */
    if ((keyCode >= 48 && event.keyCode <= 57 || keyCode === 190) && !event.shiftKey){
      const keyNum = String.fromCharCode(keyCode);
      const newExtra = {
        keyIndex,
        value: extraValue + (keyNum === '¾' ? '.' : keyNum)
      }
      setExtra(newExtra);
    }
    /* 符号 */
    const hasShift = event.shiftKey;
    const testSymbol = checkKeycode(hasShift, keyCode)
    if (testSymbol.isSymbol){
      const { symbolValue } = testSymbol
      setExtra({})
      if (extraValue.trim() !== '') {
        const newFuncNode = [...expression]
        const addNumAndSym = () => {
          const targetNumber = {
            type: 'number',
            value: extraValue
          }
          const numberNode = createNode(targetNumber)
          newFuncNode.splice(keyIndex, 0, numberNode);
          const targetSymbol = {
            type: 'symbol',
            operator: symbolValue
          }
          const symbolNode = createNode(targetSymbol)
          newFuncNode.splice(keyIndex + 1, 0, symbolNode);
          onEdit(newFuncNode)
        }
        const asyncStep = async () => {
          // await finishAdd(keyIndex)
          await addNumAndSym();
          await autoFocus(keyIndex + 1, true)
        }
        asyncStep().then()
      }else {
        const asyncStep = async () => {
          await addNode(keyIndex, 'symbol', symbolValue);
          await autoFocus(keyIndex, true)
        }
        asyncStep().then()
      }
    }
  }

  /* input onFocus 事件  */
  const inputFocus = (event, keyIndex) => {
    setFocusIndex(keyIndex)
    if (keyIndex < 0) return;
    const inputDom =inputParent.current.querySelectorAll('input');
    inputDom[keyIndex].focus()
  }
  const defaultFocus = () => {
    const inputDom =inputParent.current.querySelectorAll('input');
    if (inputDom.length > 0) inputDom[inputDom.length - 1].focus()
  }

  useEffect(() => {
    if (isEdit && symbolInfo && focusIndex !== undefined && focusIndex !== null) {
      const asyncStep = async () => {
        await addNode(focusIndex === 0 ? 0 : focusIndex, 'symbol', symbolInfo);
        if (clearSymbol) await clearSymbol();
        await autoFocus(focusIndex, true)
      }
      asyncStep().then()
    } else {
      clearSymbol()
    }
  }, [symbolInfo])

  useEffect(() => {
    if (isEdit && attrInfo && focusIndex !== undefined && focusIndex !== null) {
      if(addDevice) addDevice(attrInfo)
      const asyncStep = async () => {
        await addNode(focusIndex === 0 ? 0 :focusIndex, attrInfo.type, attrInfo);
        await clearAttr();
        await autoFocus(focusIndex, true)
      }
      asyncStep().then()
    } else {
      clearAttr()
    }
  }, [attrInfo])

  return (
    <div
      ref={inputParent}
      onClick={defaultFocus}
      className={classname(style.edit_area)}
      style={oStyle}
    >
      {extra?.keyIndex === 0 && extra?.value && (
        <div style={{marginLeft: 13,marginRight: '-5px'}}>{extra?.value}</div>
      )}
      <input
        value=""
        onClick={event => event.stopPropagation()}
        onFocus={event => inputFocus(event, 0)}
        onBlur={() => finishAdd(0)}
        onKeyDown={event => keydownAction(event, 0)}
        onChange={(event) => inputChange(event, 0)}
        className={classname(style.hide_input, style.inner_input)}
      />
      {expression?.length > 0 && expression.map((item, index) => (
        <div key={index} className={style.pos_aline_no_wrap} onClick={event => event.stopPropagation()}>
          <RuleInfo
            parentRef={inputParent}
            {...item}
            targetKey={index + 1}
          />
          {extra?.keyIndex - 1 === index && extra?.value && (
            <div
              className="pos_center"
              style={{marginLeft: 13,marginRight: '-5px'}}
            >{extra?.value}</div>
          )}
          <input
            value=""
            onFocus={event => inputFocus(event, index + 1)}
            onBlur={() => finishAdd(index + 1)}
            onKeyDown={event => keydownAction(event, index + 1)}
            onChange={(event) => inputChange(event, index + 1)}
            className={classname(style.hide_input, style.inner_input)}
          />

        </div>
      ))}
    </div>
  );
};

export default EditNode;