@/utils#download TypeScript Examples
The following examples show how to use
@/utils#download.
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 |
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 |
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 |
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>
);
}
Example #4
Source File: index.tsx From fe-v5 with Apache License 2.0 | 4 votes |
Indicator: React.FC = () => {
const { t } = useTranslation();
// 数据定义
const [form] = Form.useForm();
const tableRef = useRef(null as any);
const exportTextRef = useRef(null as any);
const [modal, setModal] = useState<boolean>(false);
const [modalType, setModalType] = useState('create');
const [exportList, setExportList] = useState([] as string[]);
const [editingKey, setEditingKey] = useState<Partial<InterfaceItem>>({});
const [query, setQuery] = useState<string>('');
const history = useHistory();
const moreOperations: MoreOptions = {
导入指标: 'import',
导出指标: 'export',
};
const optMap = {
import: t('导入'),
edit: t('编辑'),
export: t('导出'),
create: t('创建'),
}; // 弹窗操作
const handleOpen = (type: string = 'create') => {
setModalType(type);
setModal(true);
};
const handleCancel = () => {
setModal(false);
}; // 接口操作
const handleEdit = (item: InterfaceItem) => {
setEditingKey(item);
};
const handleDelete = (item) => {
deleteIndicator([item.id]).then(async (res) => {
await tableRef.current.refreshList();
message.success(t('删除指标成功'));
});
};
const handleAdd = async () => {
try {
const values = await form.validateFields();
addIndicator(values.metrics || '').then(async (res) => {
if (res && res.success) {
await tableRef.current.refreshList();
setModal(false);
message.success(t('创建指标成功'));
}
});
} catch (e) {}
}; // 更多操作
const [oType, setOType] = useState<string>(t('更多操作'));
const onSelect = (val: string): void => {
switch (val) {
case 'import':
setModal(true);
setModalType('import');
break;
case 'export':
if (exportList.length <= 0) {
message.warning(t('请勾选需要导出的指标'));
} else {
setModal(true);
setModalType('export');
setTimeout(() => {
exportTextRef.current && exportTextRef.current.focus();
});
}
break;
default:
break;
}
setOType(val);
}; // table
const handleEditChange = (e, record, index, field) => {
let targetCol = Object.assign({}, record);
targetCol[field] = e.target.value;
setEditingKey(targetCol);
};
const renderInput = (text, record, index, field) => {
if (record.id === editingKey.id) {
return (
<Input
defaultValue={text}
onPressEnter={() => handleEditOption('save')}
onChange={(e) => handleEditChange(e, record, index, field)}
/>
);
} else {
return <span>{text}</span>;
}
};
const handleEditOption = async (type = '') => {
if (type === 'save') {
let id = editingKey.id || -1;
await editIndicator(id, {
description: editingKey.description,
metric: editingKey.metric,
});
message.success(t('编辑成功'));
tableRef.current.refreshList();
}
setEditingKey({} as any);
};
const columns = [
{
title: t('指标名称'),
dataIndex: 'metric',
key: 'metric',
render: (text: string, record: InterfaceItem) => {
return (
<a
onClick={() => {
let path = {
pathname: `/metric/explorer`,
state: { name: text, description: record.description },
};
history.push(path);
}}
>
{text}
</a>
);
},
},
{
title: t('释义'),
dataIndex: 'description',
width: '40%',
key: 'description',
render: (text: string, record: InterfaceItem, index: number) => {
return renderInput(text, record, index, 'description');
},
},
{
title: t('操作'),
dataIndex: '',
key: 'operations',
width: '15%',
render: (_: any, item: any) => {
return (
<div className='operations'>
{item.id !== editingKey.id ? (
<div>
<span
className='operation-item edit'
onClick={() => handleEdit(item)}
>
{t('编辑')}
</span>
{/* <Popconfirm
title='确定删除该指标?'
onConfirm={() => handleDelete(item)}
okText='确定'
cancelText='取消'
>
<span className='operation-item delete'>删除</span>
</Popconfirm> */}
<div
className='table-operator-area-warning'
style={{
display: 'inline-block',
marginLeft: 10,
}}
onClick={() => {
confirm({
title: t('确定删除该指标?'),
icon: <ExclamationCircleOutlined />,
onOk: () => {
handleDelete(item);
},
});
}}
>
{t('删除')}
</div>
</div>
) : (
<div>
<span
className='operation-item edit-save'
onClick={() => handleEditOption('save')}
>
{t('保存')}
</span>
<span
className='operation-item edit-cancel'
onClick={() => handleEditOption('cancel')}
>
{t('取消')}
</span>
</div>
)}
</div>
);
},
},
];
const onSearchQuery = (e) => {
let val = e.target.value;
setQuery(val);
};
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
let list: string[] = [];
selectedRows.map((item) => {
list.push(`${item.metric}:${item.description}`);
});
setExportList(list);
},
};
const handleExportTxt = () => {
download(exportList);
};
return (
<PageLayout title={t('指标释义')} icon={<BulbOutlined />}>
<div className='indicator-index'>
<div className='indicator-operations'>
<Input
className={'searchInput'}
onPressEnter={onSearchQuery}
prefix={<SearchOutlined />}
placeholder={t('指标名称或释义')}
/>
<div className='operations'>
<Button.Group>
<Button
size='middle'
type='default'
icon={<DownloadOutlined />}
onClick={() => onSelect('import')}
>
{t('导入')}
</Button>
<Button
size='middle'
type='default'
icon={<UploadOutlined />}
onClick={() => onSelect('export')}
>
{t('导出')}
</Button>
</Button.Group>
</div>
</div>
<div className='indicator-main'>
<BaseTable
fetchHandle={getIndicatorList}
ref={tableRef}
fetchParams={{
query: query,
}}
rowSelection={{ ...rowSelection }}
rowKey={(record: { id: number }) => {
return record.id;
}}
columns={columns}
/>
</div>
</div>
<Modal
title={optMap[modalType]}
destroyOnClose={true}
footer={
modalType !== 'export' && [
<Button key='delete' onClick={handleCancel}>
{t('取消')}
</Button>,
<Button key='submit' type='primary' onClick={handleAdd}>
{t('确定')}
</Button>,
]
}
onCancel={handleCancel}
visible={modal}
>
<p
style={{
color: '#999',
}}
>
{modalType === 'export' ? (
<a onClick={handleExportTxt}>Download.txt</a>
) : (
<span>{t('一行一个')}</span>
)}
</p>
{(() => {
switch (modalType) {
case 'export':
return (
<div
contentEditable='true'
suppressContentEditableWarning={true}
ref={exportTextRef}
style={{
height: '200px',
border: '1px solid #d9d9d9',
overflow: 'auto',
padding: '10px',
}}
>
{exportList.map((item, index) => {
return <div key={index}>{item}</div>;
})}
</div>
);
break;
case 'import':
case 'create':
return (
<Form name={modalType + '-dialog'} form={form} preserve={false}>
<Form.Item
name={'metrics'}
key={'metrics'}
rules={[
{
required: true,
message: t('不能为空'),
validateTrigger: 'trigger',
},
]}
>
<TextArea
placeholder={'name:description'}
rows={4}
></TextArea>
</Form.Item>
</Form>
);
break;
}
})()}
</Modal>
</PageLayout>
);
}