import React from "react"; import { useBlockNoteEditor, useComponentsContext, useEditorState } from "@blocknote/react"; import { isTableCellSelection } from "@blocknote/core"; import { UploadOutlined } from '@ant-design/icons'; import { message } from "antd"; import { useLocale } from "../../../locale/useLocale"; import { richTextFileUpload } from "../constant"; import HcserviceV3 from "../../../tmpl/hcservice-v3"; import { handleFileUrl } from "../index"; import { schema } from "./schema"; const { sourceId, serverKey } = richTextFileUpload; interface Props { size?: number; } // 文本工具栏上传文件按钮 const Index = (props: Props) => { const { size } = props; const { translate } = useLocale(); const Components = useComponentsContext(); const editor = useBlockNoteEditor(); const showUploadFileButton = useEditorState({ editor, selector: ({ editor }) => { if ( !editor.isEditable || // ① 只读 editor.prosemirrorState.selection.empty || // ② 空选区 !("link" in editor.schema.inlineContentSchema) || // ③ schema 无 link isTableCellSelection(editor.prosemirrorState.selection) || // ④ 表格单元格选区 !(editor.getSelection()?.blocks || [editor.getTextCursorPosition().block]) .find((block) => block.content !== undefined) // ⑤ 块无 inline content ) { return undefined; } return { text: editor.getSelectedText() }; }, }); if (showUploadFileButton === undefined) return null; // 文件上传校验 const beforeUpload = async (file: File) => { if (size && file.size > size * 1024 * 1024) { message.warning(translate("${文件大小不能超过}") + `${size}M`); return false; } return true; } // 上传文件 const handleUploadFile = async (file: File) => { const isUpload = await beforeUpload(file); if (!isUpload) return; const fd = new FormData(); fd.append("file", file); const res = await HcserviceV3.postFile(fd); if (res.status !== "success") { message.error(translate("${文件上传失败}")); return; } const fileKey = res.fileKey; const fileName = file.name; const data = { valid: "new", fileKey, fileName }; const result = { 使用说明: fileName, 文件: JSON.stringify(data) }; const { code } = await HcserviceV3.postMstrucDtmplData(serverKey, sourceId, result, message); const imgData = await HcserviceV3.requestMstrucDtmplData(serverKey, sourceId, code, null); const basePath = JSON.parse(imgData.fieldMap["文件"] || "{}").base?.path; const fileUrl = handleFileUrl(basePath); return { url: fileUrl, basePath }; } const onClick = () => { // 打开文件对话框前先取出选中文字 const selectedText = editor.getSelectedText(); const input = document.createElement("input"); input.type = "file"; input.onchange = async () => { const file = input.files?.[0]; if (!file) return; try { const { url, basePath } = await handleUploadFile(file); editor.insertInlineContent([ { type: "fileLink", props: { href: url, basePath, label: selectedText, fileName: selectedText }, }, ]); editor.focus(); } catch (err) { message.error(translate("${文件上传失败}")); console.error("文件上传失败", err); } }; input.click(); }; return ( } onClick={onClick} /> ); } export default Index;