@/utils#copyToClipBoard TypeScript Examples

The following examples show how to use @/utils#copyToClipBoard. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Export.tsx    From fe-v5 with Apache License 2.0 6 votes vote down vote up
function Export(props: IProps & ModalWrapProps) {
  const { visible, destroy } = props;
  const [data, setData] = useState(props.data);
  return (
    <Modal
      title='导出大盘'
      visible={visible}
      onCancel={() => {
        destroy();
      }}
      footer={null}
    >
      <p>
        <a
          onClick={() => {
            download([data], 'download.json');
          }}
        >
          Download.json
        </a>
        <a style={{ float: 'right' }} onClick={() => copyToClipBoard(data, (val) => val)}>
          <CopyOutlined />
          复制JSON内容到剪贴板
        </a>
      </p>
      <Input.TextArea
        value={data}
        onChange={(e) => {
          setData(e.target.value);
        }}
        rows={15}
      />
    </Modal>
  );
}
Example #2
Source File: Export.tsx    From fe-v5 with Apache License 2.0 6 votes vote down vote up
function Export(props: ModalWrapProps & IProps) {
  const { visible, destroy, data } = props;
  const { t } = useTranslation();
  let str = data;
  try {
    str = JSON.stringify(JSON.parse(data), null, 4);
  } catch (e) {
    console.log(e);
  }

  return (
    <Modal
      title='导出配置'
      visible={visible}
      onCancel={() => {
        destroy();
      }}
      footer={null}
    >
      <>
        <div style={{ marginBottom: 10 }}>
          <a
            onClick={() => {
              download([data], 'download.json');
            }}
          >
            Download.json
          </a>
          <a style={{ float: 'right' }} onClick={() => copyToClipBoard(data, t)}>
            <CopyOutlined />
            复制JSON内容到剪贴板
          </a>
        </div>
        <Input.TextArea value={str} rows={10} />
      </>
    </Modal>
  );
}
Example #3
Source File: index.tsx    From fe-v5 with Apache License 2.0 4 votes vote down vote up
export default function ImportAndDownloadModal(props: Props) {
  const { t } = useTranslation();
  const exportTextRef = useRef(null as any);
  const { status, title, exportData, description, onClose, onSubmit, crossCluster = true, onSuccess, label, fetchBuiltinFunc, submitBuiltinFunc, bgid } = props;
  const [form] = Form.useForm();
  const { clusters: clusterList } = useSelector<RootState, CommonStoreState>((state) => state.common);
  const [allList, setAllList] = useState<{ name: string }[]>([]);
  const [buildinList, setBuildinList] = useState<{ name: string }[]>([]);
  const [importResult, setImportResult] = useState<{ name: string; isTrue: boolean; msg: string }[]>();
  const columns = [
    {
      title: label,
      dataIndex: 'name',
    },
    {
      title: '导入结果',
      dataIndex: 'isTrue',
      render: (data) => {
        return data ? <CheckCircleOutlined style={{ color: '#389e0d', fontSize: '18px' }} /> : <CloseCircleOutlined style={{ color: '#d4380d', fontSize: '18px' }} />;
      },
    },
    {
      title: '错误消息',
      dataIndex: 'msg',
    },
  ];
  const builtinColumn = [
    {
      title: `${label}名称`,
      dataIndex: 'name',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render(id, record) {
        return (
          <Button
            type='link'
            onClick={() => {
              submitBuiltinFunc &&
                submitBuiltinFunc(record.name, form.getFieldValue('cluster'), bgid!).then(({ dat }) => {
                  setImportResult(
                    Object.keys(dat).map((key) => {
                      return {
                        name: key,
                        key: key,
                        isTrue: !dat[key],
                        msg: dat[key],
                      };
                    }),
                  );
                });
            }}
          >
            导入
          </Button>
        );
      },
    },
  ];
  const handleClose = () => {
    onClose();
    importResult && importResult.some((item) => item.isTrue) && onSuccess && onSuccess();
  };
  useEffect(() => {
    if (status === ModalStatus.BuiltIn || status == ModalStatus.Import) {
      fetchBuiltinFunc &&
        fetchBuiltinFunc().then((res) => {
          let arr = res.dat.map((name) => ({ name }));
          setBuildinList(arr);
          setAllList(arr);
        });
    }
    setImportResult(undefined);
  }, [status]);

  const handleExportTxt = () => {
    download([exportData], 'download.json');
  };
  const computeTitle = isValidElement(title) ? title : status === ModalStatus.Export ? t('导出') + title : t('导入') + title;

  return (
    <Modal
      title={computeTitle}
      destroyOnClose={true}
      wrapClassName={isValidElement(title) ? 'import-modal-wrapper' : undefined}
      footer={
        status === ModalStatus.Import && (
          <>
            <Button key='delete' onClick={handleClose}>
              {t('取消')}
            </Button>
            {importResult ? (
              <Button type='primary' onClick={handleClose}>
                {t('关闭')}
              </Button>
            ) : (
              <Button
                key='submit'
                type='primary'
                onClick={async () => {
                  await form.validateFields();
                  const data = form.getFieldsValue();
                  try {
                    const importData = JSON.parse(data.import);
                    if (!Array.isArray(importData)) {
                      message.error(title + 'JSON需要时数组');
                      return;
                    }
                    const requstBody = importData.map((item) => {
                      return {
                        ...item,
                        cluster: crossCluster ? data.cluster : undefined,
                      };
                    });

                    const dat = await onSubmit(requstBody);
                    const dataSource = Object.keys(dat).map((key) => {
                      return {
                        name: key,
                        key: key,
                        isTrue: !dat[key],
                        msg: dat[key],
                      };
                    });
                    setImportResult(dataSource);
                    // 每个业务各自处理onSubmit
                  } catch (error) {
                    message.error(t('数据有误:') + error);
                  }
                }}
              >
                {t('确定')}
              </Button>
            )}
          </>
        )
      }
      onCancel={handleClose}
      afterClose={() => setImportResult(undefined)}
      visible={status !== 'hide'}
      width={600}
    >
      <div
        style={{
          color: '#999',
        }}
      >
        {description && <p>{description}</p>}
        {status === ModalStatus.Export && (
          <p>
            <a onClick={handleExportTxt}>Download.json</a>
            <a style={{ float: 'right' }} onClick={() => copyToClipBoard(exportData, t)}>
              <CopyOutlined />
              复制JSON内容到剪贴板
            </a>
          </p>
        )}
      </div>
      {(() => {
        switch (status) {
          case ModalStatus.Export:
            return (
              <div contentEditable='true' suppressContentEditableWarning={true} ref={exportTextRef} className='export-dialog code-area'>
                <pre>{exportData}</pre>
              </div>
            );

          case ModalStatus.BuiltIn:
            return (
              <>
                <Form form={form} preserve={false} layout='vertical'>
                  {crossCluster && (
                    <Form.Item
                      label={t('生效集群:')}
                      name='cluster'
                      initialValue={clusterList[0] || 'Default'}
                      rules={[
                        {
                          required: true,
                          message: t('生效集群不能为空'),
                        },
                      ]}
                    >
                      <Select suffixIcon={<CaretDownOutlined />}>
                        {clusterList?.map((item) => (
                          <Option value={item} key={item}>
                            {item}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  )}
                </Form>
                <Input
                  placeholder={`请输入要查询的${label}名称`}
                  prefix={<SearchOutlined />}
                  style={{ marginBottom: '8px' }}
                  allowClear
                  onChange={(e) => {
                    let str = e.target.value;
                    let filterArr: { name: string }[] = [];
                    allList.forEach((el) => {
                      if (el.name.toLowerCase().indexOf(str.toLowerCase()) != -1) filterArr.push(el);
                    });
                    setBuildinList(filterArr);
                  }}
                />
                <Table className='samll_table' dataSource={buildinList} columns={builtinColumn} pagination={buildinList.length < 5 ? false : { pageSize: 5 }} size='small' />
                {importResult && (
                  <>
                    <Divider />
                    <Table className='samll_table' dataSource={importResult} columns={columns} size='small' pagination={importResult.length < 5 ? false : { pageSize: 5 }} />
                  </>
                )}
              </>
            );

          case ModalStatus.Import:
            return (
              <>
                <Form form={form} preserve={false} layout='vertical'>
                  {crossCluster ? (
                    <Form.Item
                      label={t('生效集群:')}
                      name='cluster'
                      initialValue={clusterList[0] || 'Default'}
                      rules={[
                        {
                          required: true,
                          message: t('生效集群不能为空'),
                        },
                      ]}
                    >
                      <Select suffixIcon={<CaretDownOutlined />}>
                        {clusterList?.map((item) => (
                          <Option value={item} key={item}>
                            {item}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  ) : null}
                  <Form.Item
                    label={(!isValidElement(title) ? title : label) + t('JSON:')}
                    name='import'
                    rules={[
                      {
                        required: true,
                        message: t('请输入') + title,
                        validateTrigger: 'trigger',
                      },
                    ]}
                  >
                    <TextArea className='code-area' placeholder={t('请输入') + (!isValidElement(title) ? title : label)} rows={4}></TextArea>
                  </Form.Item>
                </Form>
                {importResult && (
                  <>
                    <Divider />
                    <Table className='samll_table' dataSource={importResult} columns={columns} pagination={false} size='small' />
                  </>
                )}
              </>
            );
        }
      })()}
    </Modal>
  );
}