import React, { useRef, useState } from "react"; import { createReactInlineContentSpec, useEditorState } from "@blocknote/react"; import { PictureOutlined } from "@ant-design/icons"; import { handleFileUrl } from "../index"; import "./index.less"; const MIN_WIDTH = 24; // 最小宽度(px),防止拖成一条线 /** * 自定义「行内图片」节点: * - inline 节点,可插在文字中间(「见图 1 所示」这种引用) * - url / alt / width 持久化在文档数据里 * - 支持拖拽右下角把手调整宽度;width = 0 表示自动(受 CSS max-height 约束,不撑高行) * * 拖拽实现要点: * - 拖动过程中直接改 DOM 的 style.width(流畅,不触发文档事务) * - 松手时才调用 updateInlineContent 写入 props(避免每次 mousemove 都产生一步历史) */ const InlineImage = createReactInlineContentSpec( { type: "inlineImage", propSchema: { url: { default: "" }, // 图片地址(上传后回填) basePath: { default: "" }, // 基础文件地址(持久化存储) alt: { default: "" }, // 无障碍描述 / 原始文件名 width: { default: 0 }, // 0 = 自动;>0 = 用户拖拽后的固定宽度(px) }, content: "none", }, { render: ({ inlineContent, updateInlineContent, editor }) => { const { url, basePath, alt, width } = inlineContent.props; const temUrl = basePath ? handleFileUrl(basePath) : url; const imgRef = useRef(null); const [resizing, setResizing] = useState(false); const latestWidth = useRef(width); // 用 useEditorState 订阅,editable 切换时能实时响应 const editable = useEditorState({ editor, selector: ({ editor }) => editor.isEditable, }); // 空地址(上传中/失败)时不渲染破图 if (!temUrl) { return ( ); } const startResize = (e: React.PointerEvent) => { if (!editable) return; // 双保险,即使事件被触发也不动 // 阻止 ProseMirror 抢走事件(否则会变成选文字) e.preventDefault(); e.stopPropagation(); const startX = e.clientX; const startWidth = imgRef.current?.offsetWidth ?? 0; latestWidth.current = startWidth; setResizing(true); const onMove = (ev: PointerEvent) => { const next = Math.max(MIN_WIDTH, Math.round(startWidth + ev.clientX - startX)); latestWidth.current = next; if (imgRef.current) imgRef.current.style.width = `${next}px`; }; const onUp = () => { window.removeEventListener("pointermove", onMove); window.removeEventListener("pointerup", onUp); setResizing(false); // 交回 props 控制(先清掉临时内联样式,避免和 props 打架) if (imgRef.current) imgRef.current.style.width = ""; if (latestWidth.current !== width) { // 注意:props 必须传全量(url / alt / width),且要带 type updateInlineContent({ type: "inlineImage", props: { url, basePath, alt, width: latestWidth.current }, }); } }; window.addEventListener("pointermove", onMove); window.addEventListener("pointerup", onUp); } const resizingStyle = resizing ? { maxHeight: "none", height: "auto" } : {}; const imgWidthStyle = width ? { width: `${width}px`, maxHeight: "none", height: "auto" } : {}; const imgStyle = { display: "inline-block", height: "1.6em", width: "auto", maxWidth: "100%", verticalAlign: "middle", borderRadius: "4px", "object-fit": "contain" }; return ( {alt} updateInlineContent({ type: "inlineImage", props: { url, basePath, alt, width: 0 }, }) } title={width ? "双击恢复自动尺寸" : alt} /> {editable && } ); } } ); export default InlineImage;