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.

242 lines (237 loc) 14.2 kB
'use client'; var _excluded = ["fontSize", "headerMultiple", "lineHeight", "marginMultiple"]; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } 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; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } import { cx } from 'antd-style'; import { COMMAND_PRIORITY_EDITOR, KEY_DOWN_COMMAND } from 'lexical'; import { Children, memo, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { useMemo } from 'react'; import { LexicalErrorBoundary } from "../../../editor-kernel/react/LexicalErrorBoundary"; import { useLexicalComposerContext } from "../../../editor-kernel/react/react-context"; import { useDecorators } from "../../../editor-kernel/react/useDecorators"; import { MarkdownPlugin } from "../../markdown/plugin"; import { CommonPlugin } from "../plugin"; import Placeholder from "./Placeholder"; import { styles, themeStyles } from "./style"; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; // Keep memo: Core editor rendering layer with complex event handling and decorator management var ReactPlainText = /*#__PURE__*/memo(function (_ref) { var style = _ref.style, children = _ref.children, _ref$theme = _ref.theme, theme = _ref$theme === void 0 ? {} : _ref$theme, onChange = _ref.onChange, editable = _ref.editable, className = _ref.className, variant = _ref.variant, _ref$enableHotkey = _ref.enableHotkey, enableHotkey = _ref$enableHotkey === void 0 ? true : _ref$enableHotkey, _ref$enablePasteMarkd = _ref.enablePasteMarkdown, enablePasteMarkdown = _ref$enablePasteMarkd === void 0 ? true : _ref$enablePasteMarkd, _ref$markdownOption = _ref.markdownOption, markdownOption = _ref$markdownOption === void 0 ? true : _ref$markdownOption, onKeyDown = _ref.onKeyDown, onFocus = _ref.onFocus, onBlur = _ref.onBlur, autoFocus = _ref.autoFocus, onPressEnter = _ref.onPressEnter, onCompositionStart = _ref.onCompositionStart, onCompositionEnd = _ref.onCompositionEnd, onContextMenu = _ref.onContextMenu, onTextChange = _ref.onTextChange; var isChat = variant === 'chat'; var _theme$fontSize = theme.fontSize, fontSize = _theme$fontSize === void 0 ? isChat ? 14 : 16 : _theme$fontSize, _theme$headerMultiple = theme.headerMultiple, headerMultiple = _theme$headerMultiple === void 0 ? isChat ? 0.25 : 0.6 : _theme$headerMultiple, _theme$lineHeight = theme.lineHeight, lineHeight = _theme$lineHeight === void 0 ? isChat ? 1.4 : 1.6 : _theme$lineHeight, _theme$marginMultiple = theme.marginMultiple, marginMultiple = _theme$marginMultiple === void 0 ? isChat ? 1 : 2 : _theme$marginMultiple, restTheme = _objectWithoutProperties(theme, _excluded); var editorContainerRef = useRef(null); var _useLexicalComposerCo = useLexicalComposerContext(), _useLexicalComposerCo2 = _slicedToArray(_useLexicalComposerCo, 1), editor = _useLexicalComposerCo2[0]; var decorators = useDecorators(editor, LexicalErrorBoundary); var cssVariables = useMemo(function () { return { '--common-font-size': "".concat(fontSize, "px"), '--common-header-multiple': String(headerMultiple), '--common-line-height': String(lineHeight), '--common-margin-multiple': String(marginMultiple) }; }, [fontSize, headerMultiple, marginMultiple, lineHeight]); var computedThemeStyles = useMemo(function () { var bold = markdownOption === true || _typeof(markdownOption) === 'object' && markdownOption.bold === true; var italic = markdownOption === true || _typeof(markdownOption) === 'object' && markdownOption.italic === true; var strikethrough = markdownOption === true || _typeof(markdownOption) === 'object' && markdownOption.strikethrough === true; var underline = markdownOption === true || _typeof(markdownOption) === 'object' && markdownOption.underline === true; var underlineStrikethrough = markdownOption === true || _typeof(markdownOption) === 'object' && markdownOption.underlineStrikethrough === true; return { quote: themeStyles.quote, textBold: bold ? themeStyles.textBold_true : themeStyles.textBold_false, textCode: themeStyles.textCode, textItalic: italic ? themeStyles.textItalic_true : themeStyles.textItalic_false, textStrikethrough: strikethrough ? themeStyles.textStrikethrough_true : themeStyles.textStrikethrough_false, textUnderline: underline ? themeStyles.textUnderline_true : themeStyles.textUnderline_false, textUnderlineStrikethrough: underlineStrikethrough ? themeStyles.textUnderlineStrikethrough_true : themeStyles.textUnderlineStrikethrough_false }; }, [markdownOption]); var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), isInitialized = _useState2[0], setIsInitialized = _useState2[1]; var _Children$only = Children.only(children), _Children$only$props = _Children$only.props, type = _Children$only$props.type, content = _Children$only$props.content, placeholder = _Children$only$props.placeholder, lineEmptyPlaceholder = _Children$only$props.lineEmptyPlaceholder; useLayoutEffect(function () { editor.registerPlugin(MarkdownPlugin, { enablePasteMarkdown: enablePasteMarkdown }); editor.registerPlugin(CommonPlugin, { enableHotkey: enableHotkey, markdownOption: markdownOption, theme: restTheme ? _objectSpread(_objectSpread({}, computedThemeStyles), restTheme) : computedThemeStyles }); }, [editor, enableHotkey, enablePasteMarkdown, markdownOption, restTheme, computedThemeStyles]); useEffect(function () { var _editor$getLexicalEdi; var container = editorContainerRef.current; if (container && !isInitialized) { // Initialize the editor editor.setRootElement(container, editable); // Set initial document content only once editor.setDocument(type, content); setIsInitialized(true); } // Track previous content for onTextChange comparison var previousContent; return (_editor$getLexicalEdi = editor.getLexicalEditor()) === null || _editor$getLexicalEdi === void 0 ? void 0 : _editor$getLexicalEdi.registerUpdateListener(function (_ref2) { var dirtyElements = _ref2.dirtyElements, dirtyLeaves = _ref2.dirtyLeaves; // Always trigger onChange for any update onChange === null || onChange === void 0 || onChange(editor); // Only trigger onTextChange when content actually changes if (onTextChange && (dirtyElements.size > 0 || dirtyLeaves.size > 0)) { var currentContent = JSON.stringify(editor.getDocument(type)); if (previousContent === undefined) { // First update after initialization previousContent = currentContent; } else if (currentContent !== previousContent) { // Content has actually changed previousContent = currentContent; onTextChange(editor); } } }); }, [editor, type, content, onChange, onTextChange, isInitialized]); useEffect(function () { var handleDocumentChange = function handleDocumentChange() { onTextChange === null || onTextChange === void 0 || onTextChange(editor); }; editor.on('documentChange', handleDocumentChange); return function () { editor.off('documentChange', handleDocumentChange); }; }, [editor, onTextChange]); useEffect(function () { if (!isInitialized) return; if (typeof editable === 'boolean') { editor.setEditable(editable); } }, [isInitialized, editable]); useEffect(function () { if (editor && onPressEnter) { return editor.registerHighCommand(KEY_DOWN_COMMAND, function (event) { if (event.key === 'Enter' && !event.isComposing && onPressEnter({ editor: editor, event: event })) { event.preventDefault(); return true; // Indicate that the event has been handled } // if (onKeyDown !== null && onKeyDown !== void 0 && onKeyDown({ editor: editor, event: event })) { event.preventDefault(); return true; // Indicate that the event has been handled } return false; // Allow other handlers to process the event }, COMMAND_PRIORITY_EDITOR); } }, [editor, onPressEnter, onKeyDown]); useEffect(function () { if (autoFocus && editorContainerRef.current) { editorContainerRef.current.focus(); } }, [autoFocus]); var handleBlur = function handleBlur(event) { onBlur === null || onBlur === void 0 || onBlur({ editor: editor, event: event }); }; var handleCompositionEnd = function handleCompositionEnd(event) { onCompositionEnd === null || onCompositionEnd === void 0 || onCompositionEnd({ editor: editor, event: event }); }; var handleCompositionStart = function handleCompositionStart(event) { onCompositionStart === null || onCompositionStart === void 0 || onCompositionStart({ editor: editor, event: event }); }; var handleContextMenu = function handleContextMenu(event) { onContextMenu === null || onContextMenu === void 0 || onContextMenu({ editor: editor, event: event }); }; var handleFocus = function handleFocus(event) { onFocus === null || onFocus === void 0 || onFocus({ editor: editor, event: event }); }; return /*#__PURE__*/_jsxs("div", { className: cx(styles.root, styles.variant, className), style: _objectSpread(_objectSpread({}, cssVariables), style), children: [/*#__PURE__*/_jsx("div", { className: styles.editorContent, contentEditable: editable !== null && editable !== void 0 ? editable : true, onBlur: handleBlur, onCompositionEnd: handleCompositionEnd, onCompositionStart: handleCompositionStart, onContextMenu: handleContextMenu, onFocus: handleFocus, ref: editorContainerRef }), /*#__PURE__*/_jsx(Placeholder, { lineEmptyPlaceholder: lineEmptyPlaceholder, style: style, children: placeholder }), decorators] }); }); ReactPlainText.displayName = 'ReactPlainText'; export default ReactPlainText;