UNPKG

@lobehub/editor

Version:

A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.

234 lines (218 loc) 9.37 kB
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } import { cx } from 'antd-style'; import { COMMAND_PRIORITY_LOW, SELECTION_CHANGE_COMMAND } from 'lexical'; import React, { memo, useCallback, useMemo, useRef, useState } from 'react'; import { useLexicalEditor } from "../../../../editor-kernel/react/useLexicalEditor"; import { useLexicalNodeSelection } from "../../../../editor-kernel/react/useLexicalNodeSelection"; import { $isBlockImageNode } from "../../node/block-image-node"; import BrokenImage from "./BrokenImage"; import LazyImage from "./LazyImage"; import { ResizeHandle } from "./ResizeHandle"; import { styles } from "./style"; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; import { Fragment as _Fragment } from "react/jsx-runtime"; // Keep memo: Complex resize logic, state management, and multiple event handlers var Image = /*#__PURE__*/memo(function (_ref) { var node = _ref.node, className = _ref.className, _ref$showScaleInfo = _ref.showScaleInfo, showScaleInfo = _ref$showScaleInfo === void 0 ? false : _ref$showScaleInfo; var _useLexicalNodeSelect = useLexicalNodeSelection(node.getKey()), _useLexicalNodeSelect2 = _slicedToArray(_useLexicalNodeSelect, 2), isSelected = _useLexicalNodeSelect2[0], setSelected = _useLexicalNodeSelect2[1]; var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), isHovered = _useState2[0], setIsHovered = _useState2[1]; var _useState3 = useState(1), _useState4 = _slicedToArray(_useState3, 2), scale = _useState4[0], setScale = _useState4[1]; var _useState5 = useState({ height: 0, width: 0 }), _useState6 = _slicedToArray(_useState5, 2), size = _useState6[0], setSize = _useState6[1]; var _useState7 = useState(null), _useState8 = _slicedToArray(_useState7, 2), newWidth = _useState8[0], setNewWidth = _useState8[1]; var imageRef = useRef(null); var originalSizeRef = useRef({ height: 0, width: 0 }); var editorRef = useRef(null); var startWidthRef = useRef(0); var isBlock = useMemo(function () { return $isBlockImageNode(node); }, [node]); useLexicalEditor(function (editor) { editorRef.current = editor; var unregister = editor.registerCommand(SELECTION_CHANGE_COMMAND, // eslint-disable-next-line @typescript-eslint/no-unused-vars function (_, _activeEditor) { return false; }, COMMAND_PRIORITY_LOW); return function () { editorRef.current = null; unregister(); }; }, []); // Resize by dragging - only control width; height is calculated by aspect ratio var handleResize = useCallback(function (deltaX) { var _imageRef$current$par; if (!originalSizeRef.current.width || !originalSizeRef.current.height) return; if (!imageRef.current) return; var aspectRatio = originalSizeRef.current.width / originalSizeRef.current.height; // Get parent container width to limit max width var parentWidth = ((_imageRef$current$par = imageRef.current.parentElement) === null || _imageRef$current$par === void 0 ? void 0 : _imageRef$current$par.clientWidth) || window.innerWidth; var maxWidth = parentWidth; // Since image is centered, delta is halved (both sides resize) var adjustedDeltaX = deltaX * 2; // Use the width captured at mousedown time var newWidth = Math.max(50, Math.min(startWidthRef.current + adjustedDeltaX, maxWidth)); // Calculate new height based on the original aspect ratio var newHeight = newWidth / aspectRatio; setSize({ height: newHeight, width: newWidth }); setNewWidth(newWidth); // Update the scale var newScale = newWidth / originalSizeRef.current.width; setScale(newScale); }, []); // Store the initial width when resize starts var handleResizeStart = useCallback(function (initialWidth) { startWidthRef.current = initialWidth; }, []); // Click to select var handleClick = useCallback(function (e) { e.stopPropagation(); setSelected(true); }, [setSelected]); // Double-click to reset to original size and aspect ratio var handleDoubleClick = useCallback(function (e) { var editor = editorRef.current; if (!editor) return; e.stopPropagation(); e.preventDefault(); var orig = originalSizeRef.current; if (!orig.width || !orig.height) return; setSize(orig); setScale(1); setNewWidth(orig.width); editor.update(function () { try { node.setWidth(orig.width); node.setMaxWidth(orig.width); } catch (_unused) { // ignore errors silently } }); }, []); // Mouse enter handler var handleMouseEnter = useCallback(function () { setIsHovered(true); }, []); // Mouse leave handler var handleMouseLeave = useCallback(function () { setIsHovered(false); }, []); var children = useMemo(function () { switch (node.status) { case 'error': { return /*#__PURE__*/_jsx(BrokenImage, {}); } case 'uploaded': case 'loading': { return /*#__PURE__*/_jsx(LazyImage, { className: className, newWidth: newWidth, node: node, onLoad: function onLoad(size) { originalSizeRef.current.width = size.width; originalSizeRef.current.height = size.height; setSize(size); } }); } default: { return null; } } }, [node.status, className, node, newWidth]); // On resize end, persist to node (set maxWidth) var handleResizeEnd = useCallback(function (deltaX) { var _imageRef$current$par2; if (!originalSizeRef.current.width || !originalSizeRef.current.height) return; if (!imageRef.current) return; // Get parent container width to limit max width var parentWidth = ((_imageRef$current$par2 = imageRef.current.parentElement) === null || _imageRef$current$par2 === void 0 ? void 0 : _imageRef$current$par2.clientWidth) || window.innerWidth; var maxWidth = parentWidth; // Since image is centered, delta is halved (both sides resize) var adjustedDeltaX = deltaX / 2; // Use the width captured at mousedown time var finalWidth = Math.max(50, Math.min(startWidthRef.current + adjustedDeltaX, maxWidth)); // persist to node via editor.update var editor = editorRef.current; if (!editor) return; editor.update(function () { try { node.setWidth(finalWidth); node.setMaxWidth(finalWidth); } catch (_unused2) { // ignore errors silently } }); }, [node]); return /*#__PURE__*/_jsxs("div", { className: cx(styles.imageContainer, { selected: isSelected }), draggable: false, onClick: handleClick, onDoubleClick: handleDoubleClick, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, ref: imageRef, style: { width: size.width || 'auto' }, children: [children, showScaleInfo && isSelected && scale !== 1 && /*#__PURE__*/_jsxs("div", { className: styles.scaleInfo, children: [Math.round(scale * 100), "%"] }), isHovered && node.status === 'uploaded' && /*#__PURE__*/_jsxs(_Fragment, { children: [/*#__PURE__*/_jsx(ResizeHandle, { imageRef: imageRef, isBlock: isBlock, onResize: handleResize, onResizeEnd: handleResizeEnd, onResizeStart: handleResizeStart, position: "left" }), /*#__PURE__*/_jsx(ResizeHandle, { imageRef: imageRef, isBlock: isBlock, onResize: handleResize, onResizeEnd: handleResizeEnd, onResizeStart: handleResizeStart, position: "right" })] })] }); }); Image.displayName = 'Image'; export default Image;