index.tsx 2.72 KB
// 数据流名称编辑通用组件
import React, { useEffect, useState } from 'react';
import { Input, Typography } from 'antd';
import { QxIcon } from '@/components';

const { Text } = Typography;
// 样式
import cls from 'classnames';
import styles from './index.module.less';

const prefix = 'qx-name-editor';

interface FlowNameEditorProps {
  noValueView?: string; // 无名称 展示文本
  nodeName: string; // 节点名称
  nodeIcon?: React.ReactNode; // 节点 icon
  editTitle: boolean; // 可编辑 参数
  setEditTitle: (val: boolean) => void; // 可编辑 参数
  onChange: (data: string) => void; // 名称变化调用方法
  nameMaxLength?: number; // 名称最长多少 展示省略号 默认 8
}

const FlowNameEditor: React.FC<FlowNameEditorProps> = (props) => {
  const {
    noValueView = '未命名',
    nodeName,
    nodeIcon,
    editTitle,
    setEditTitle,
    onChange,
    nameMaxLength,
  } = props;

  const [nameLocal, setNameLocal] = useState<string>('');

  const inputRef = React.useRef<any>(null);

  useEffect(() => {
    setNameLocal(nodeName);
  }, [nodeName]);

  useEffect(() => {
    if (Boolean(editTitle)) {
      inputRef.current!.focus({
        cursor: 'end',
      });
    }
  }, [editTitle]);

  return (
    <div className={cls(styles[`${prefix}`])}>
      {!!nodeIcon ? nodeIcon : null}
      {editTitle ? (
        <Input
          ref={inputRef}
          className={cls(styles[`${prefix}__input`])}
          style={{
            maxWidth: (nameMaxLength || 8) * 16 * 1.2 + 20 + 'px',
          }}
          value={nameLocal}
          maxLength={20}
          onChange={(e) => setNameLocal(e.target.value)}
          onPressEnter={() => {
            setEditTitle(false);
            if (!nameLocal) {
              setNameLocal(nodeName);
            }
            onChange(nameLocal || nodeName);
          }}
          onBlur={() => {
            setEditTitle(false);
            if (!nameLocal) {
              setNameLocal(nodeName);
            }
            onChange(nameLocal || nodeName);
          }}
        />
      ) : (
        <>
          <div
            className={cls(styles[`${prefix}__title`])}
            onClick={() => setEditTitle(true)}
          >
            <Text
              style={{ maxWidth: (nameMaxLength || 8) * 16 * 1.2 + 'px' }}
              ellipsis={{
                tooltip: nameLocal ? nameLocal : noValueView ? noValueView : '',
              }}
            >
              {nameLocal ? nameLocal : noValueView ? noValueView : ''}
            </Text>
            <QxIcon
              className={cls(styles[`${prefix}__title--edit`])}
              type={'icon-frame-edit'}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default FlowNameEditor;