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.

493 lines (483 loc) 24 kB
var _class; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } 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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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); } import { registerDragonSupport } from '@lexical/dragon'; import { registerHistory } from '@lexical/history'; import { $createHeadingNode, $createQuoteNode, $isHeadingNode, $isQuoteNode, HeadingNode, QuoteNode, registerRichText } from '@lexical/rich-text'; import { CAN_USE_DOM } from '@lexical/utils'; import { $createLineBreakNode, $createParagraphNode, $getSelection, $isRangeSelection, $isTextNode, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_HIGH, INSERT_LINE_BREAK_COMMAND, INSERT_PARAGRAPH_COMMAND, PASTE_COMMAND, ParagraphNode, TEXT_TYPE_TO_FORMAT, TextNode } from 'lexical'; import { noop } from "../../../editor-kernel"; import { INodeHelper } from "../../../editor-kernel/inode/helper"; import { KernelPlugin } from "../../../editor-kernel/plugin"; import { ILitexmlService } from "../../litexml"; import { IMarkdownShortCutService } from "../../markdown/service/shortcut"; import { isPunctuationChar } from "../../markdown/utils"; import { registerCommands } from "../command"; import JSONDataSource from "../data-source/json-data-source"; import TextDataSource from "../data-source/text-data-source"; import { patchBreakLine, registerBreakLineClick } from "../node/ElementDOMSlot"; import { CursorNode, registerCursorNode } from "../node/cursor"; import { $isCursorInQuote, $isCursorInTable, createBlockNode, sampleReader } from "../utils"; import { registerMDReader } from "./mdReader"; import { registerHeaderBackspace, registerLastElement, registerRichKeydown } from "./register"; patchBreakLine(); export var CommonPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) { _inherits(CommonPlugin, _KernelPlugin); var _super = _createSuper(CommonPlugin); function CommonPlugin(kernel) { var _this; var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, CommonPlugin); _this = _super.call(this); // Register the JSON data source _this.kernel = kernel; _this.config = config; kernel.registerDataSource(new JSONDataSource('json')); // Register the text data source kernel.registerDataSource(new TextDataSource('text')); // Register common nodes and themes kernel.registerNodes([HeadingNode, QuoteNode, CursorNode]); if (config !== null && config !== void 0 && config.theme) { kernel.registerThemes({ quote: config.theme.quote, text: { bold: config.theme.textBold, code: config.theme.textCode, highlight: config.theme.textHighlight, italic: config.theme.textItalic, strikethrough: config.theme.textStrikethrough, subscript: config.theme.textSubscript, superscript: config.theme.textSuperscript, underline: config.theme.textUnderline, underlineStrikethrough: config.theme.textUnderlineStrikethrough } }); } return _this; } _createClass(CommonPlugin, [{ key: "registerMarkdown", value: function registerMarkdown(kernel) { var _this$config$markdown, _this$config; var markdownService = kernel.requireService(IMarkdownShortCutService); if (!markdownService) { return; } // Parse markdown options var markdownOption = (_this$config$markdown = (_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.markdownOption) !== null && _this$config$markdown !== void 0 ? _this$config$markdown : true; var isMarkdownEnabled = markdownOption !== false; var breakMark = isMarkdownEnabled ? '\n\n' : '\n'; // Determine which formats are enabled var formats = { bold: true, header: true, italic: true, quote: true, strikethrough: true, subscript: false, // Disabled by default superscript: false // Disabled by default // Note: code, underline, underlineStrikethrough are handled by other plugins/writers }; if (_typeof(markdownOption) === 'object') { var _markdownOption$bold, _markdownOption$heade, _markdownOption$itali, _markdownOption$quote, _markdownOption$strik, _markdownOption$subsc, _markdownOption$super; formats.bold = (_markdownOption$bold = markdownOption.bold) !== null && _markdownOption$bold !== void 0 ? _markdownOption$bold : true; formats.header = (_markdownOption$heade = markdownOption.header) !== null && _markdownOption$heade !== void 0 ? _markdownOption$heade : true; formats.italic = (_markdownOption$itali = markdownOption.italic) !== null && _markdownOption$itali !== void 0 ? _markdownOption$itali : true; formats.quote = (_markdownOption$quote = markdownOption.quote) !== null && _markdownOption$quote !== void 0 ? _markdownOption$quote : true; formats.strikethrough = (_markdownOption$strik = markdownOption.strikethrough) !== null && _markdownOption$strik !== void 0 ? _markdownOption$strik : true; formats.subscript = (_markdownOption$subsc = markdownOption.subscript) !== null && _markdownOption$subsc !== void 0 ? _markdownOption$subsc : false; formats.superscript = (_markdownOption$super = markdownOption.superscript) !== null && _markdownOption$super !== void 0 ? _markdownOption$super : false; } // Register quote shortcut if enabled if (formats.quote) { markdownService.registerMarkdownShortCut({ regExp: /^>\s/, replace: function replace(parentNode, children, _match, isImport) { if (isImport) { var previousNode = parentNode.getPreviousSibling(); if ($isQuoteNode(previousNode)) { previousNode.splice(previousNode.getChildrenSize(), 0, [$createLineBreakNode()].concat(_toConsumableArray(children))); parentNode.remove(); return; } } var node = $createQuoteNode(); node.append.apply(node, _toConsumableArray(children)); parentNode.replace(node); if (!isImport) { node.select(0, 0); } }, type: 'element' }); } // Register header shortcut if enabled if (formats.header) { markdownService.registerMarkdownShortCut({ regExp: /^(#{1,6})\s/, replace: createBlockNode(function (match, parentNode) { var tag = 'h' + match[1].length; if ($isHeadingNode(parentNode) && parentNode.getTag() === tag) { return $createParagraphNode(); } return $createHeadingNode(tag); }), type: 'element' }); } // Register text format shortcuts based on enabled formats var textFormatShortcuts = []; if (formats.bold) { textFormatShortcuts.push({ format: ['bold'], tag: '**', type: 'text-format' }, { format: ['bold'], intraword: false, tag: '__', type: 'text-format' }); } if (formats.strikethrough) { textFormatShortcuts.push({ format: ['strikethrough'], tag: '~~', type: 'text-format' }); } if (formats.italic) { textFormatShortcuts.push({ format: ['italic'], tag: '*', type: 'text-format' }, { format: ['italic'], intraword: false, tag: '_', type: 'text-format' }); } if (formats.superscript) { textFormatShortcuts.push({ format: ['superscript'], tag: '^', type: 'text-format' }); } if (formats.subscript) { textFormatShortcuts.push({ format: ['subscript'], tag: '~', type: 'text-format' }); } if (textFormatShortcuts.length > 0) { markdownService.registerMarkdownShortCuts(textFormatShortcuts); } markdownService.registerMarkdownWriter('paragraph', function (ctx) { ctx.wrap('', '\n\n'); }); markdownService.registerMarkdownWriter('quote', function (ctx, node) { if ($isQuoteNode(node)) { ctx.wrap('> ', breakMark); } }); markdownService.registerMarkdownWriter('heading', function (ctx, node) { if ($isHeadingNode(node)) { switch (node.getTag()) { case 'h1': { ctx.wrap('# ', breakMark); break; } case 'h2': { ctx.wrap('## ', breakMark); break; } case 'h3': { ctx.wrap('### ', breakMark); break; } case 'h4': { ctx.wrap('#### ', breakMark); break; } case 'h5': { ctx.wrap('##### ', breakMark); break; } case 'h6': { ctx.wrap('###### ', breakMark); break; } default: { ctx.wrap('', '\n'); break; } } } }); markdownService.registerMarkdownWriter('text', function (ctx, node) { if (!$isTextNode(node)) { return; } var isBold = node.hasFormat('bold'); var isItalic = node.hasFormat('italic'); var isUnderline = node.hasFormat('underline'); var isStrikethrough = node.hasFormat('strikethrough'); var isSuperscript = node.hasFormat('superscript'); var isSubscript = node.hasFormat('subscript'); if (isBold) { ctx.appendLine('**'); } if (isStrikethrough) { ctx.appendLine('~~'); } if (isItalic) { ctx.appendLine('_'); } if (isUnderline) { ctx.appendLine('<ins>'); } if (isSuperscript) { ctx.appendLine('^'); } if (isSubscript) { ctx.appendLine('~'); } var textContent = node.getTextContent(); var res = textContent.match(/\s+$/); var tailSpace = ''; if (res) { tailSpace = res[0]; } var append = textContent.trimEnd(); var lastChar = append.at(-1); ctx.appendLine(append); if (isSubscript) { ctx.appendLine('~'); } if (isSuperscript) { ctx.appendLine('^'); } if (isUnderline) { ctx.appendLine('</ins>'); } if (isItalic) { ctx.appendLine('_'); } if (isStrikethrough) { ctx.appendLine('~~'); } if (isBold) { ctx.appendLine('**'); } if (tailSpace) { ctx.appendLine(tailSpace); } else if (lastChar && isPunctuationChar(lastChar)) { ctx.appendLine(' '); } }); // Register markdown writer for linebreak nodes (soft line breaks) markdownService.registerMarkdownWriter('linebreak', function (ctx) { // In markdown, soft line breaks are represented as two spaces followed by a newline ctx.appendLine(' \n'); }); // 注册 markdown reader // registerMDReader(markdownService); } }, { key: "onInit", value: function onInit(editor) { var _this2 = this, _this$config2; this.register(this.kernel.registerHighCommand(PASTE_COMMAND, function (event) { if (!(event instanceof ClipboardEvent)) return false; var clipboardData = event.clipboardData; if (!clipboardData) return false; _this2.kernel.emit('onPaste', event); return false; }, COMMAND_PRIORITY_CRITICAL)); this.registerClears(registerRichText(editor), CAN_USE_DOM ? registerDragonSupport(editor) : noop, registerHistory(editor, this.kernel.getHistoryState(), 300), registerHeaderBackspace(editor), registerRichKeydown(editor, this.kernel, { enableHotkey: (_this$config2 = this.config) === null || _this$config2 === void 0 ? void 0 : _this$config2.enableHotkey }), registerCommands(editor), registerBreakLineClick(editor), registerCursorNode(editor), registerLastElement(editor), // Convert soft line breaks (Shift+Enter) to hard line breaks (paragraph breaks) // This allows breaking out of code blocks with Shift+Enter editor.registerCommand(INSERT_LINE_BREAK_COMMAND, function () { // editor.getEditorState().read(() => { var selection = $getSelection(); if (!$isRangeSelection(selection)) { return false; } // Check if cursor is in a table var _$isCursorInTable = $isCursorInTable(selection), inCell = _$isCursorInTable.inCell, inTable = _$isCursorInTable.inTable; if (inCell) { // We're in a table cell, allow normal line break behavior return false; } if (inTable) { // We're in a table but not in a cell, prevent line break return false; } // Check if cursor is in a quote var inQuote = $isCursorInQuote(selection); if (inQuote) { // We're in a quote block, allow normal line break behavior // This preserves line breaks within quotes while maintaining quote formatting return false; } // Not in a table or quote, convert to paragraph break editor.update(function () { editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined); }); return true; // Prevent default line break behavior }, COMMAND_PRIORITY_HIGH)); this.registerMarkdown(this.kernel); this.registerLiteXml(); } }, { key: "registerLiteXml", value: function registerLiteXml() { var litexmlService = this.kernel.requireService(ILitexmlService); if (!litexmlService) { return; } litexmlService.registerXMLWriter(TextNode.getType(), function (node, ctx) { var attr = {}; if ($isTextNode(node)) { if (node.hasFormat('bold')) { attr['bold'] = 'true'; } if (node.hasFormat('italic')) { attr['italic'] = 'true'; } if (node.hasFormat('underline')) { attr['underline'] = 'true'; } if (node.hasFormat('strikethrough')) { attr['strikethrough'] = 'true'; } if (node.hasFormat('subscript')) { attr['subscript'] = 'true'; } if (node.hasFormat('superscript')) { attr['superscript'] = 'true'; } return ctx.createXmlNode('span', attr, node.getTextContent()); } return false; }); litexmlService.registerXMLReader('b', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['bold'])); litexmlService.registerXMLReader('strong', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['bold'])); litexmlService.registerXMLReader('i', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['italic'])); litexmlService.registerXMLReader('emphasis', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['italic'])); litexmlService.registerXMLReader('u', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['underline'])); litexmlService.registerXMLReader('ins', sampleReader.bind(this, TEXT_TYPE_TO_FORMAT['underline'])); litexmlService.registerXMLReader('span', function (xmlElement, children) { var bold = xmlElement.getAttribute('bold'); var italic = xmlElement.getAttribute('italic'); var underline = xmlElement.getAttribute('underline'); var strikethrough = xmlElement.getAttribute('strikethrough'); var subscript = xmlElement.getAttribute('subscript'); var superscript = xmlElement.getAttribute('superscript'); var format = 0; if (bold === 'true') { format |= TEXT_TYPE_TO_FORMAT['bold']; } if (italic === 'true') { format |= TEXT_TYPE_TO_FORMAT['italic']; } if (underline === 'true') { format |= TEXT_TYPE_TO_FORMAT['underline']; } if (strikethrough === 'true') { format |= TEXT_TYPE_TO_FORMAT['strikethrough']; } if (subscript === 'true') { format |= TEXT_TYPE_TO_FORMAT['subscript']; } if (superscript === 'true') { format |= TEXT_TYPE_TO_FORMAT['superscript']; } children.forEach(function (child) { if (INodeHelper.isTextNode(child)) { child.format = (child.format || 0) | format; } }); return children; }); litexmlService.registerXMLWriter('quote', function (node, ctx) { if ($isQuoteNode(node)) { return ctx.createXmlNode('quote', {}); } return false; }); litexmlService.registerXMLWriter('heading', function (node, ctx) { if ($isHeadingNode(node)) { return ctx.createXmlNode(node.getTag(), {}); } return false; }); litexmlService.registerXMLWriter(ParagraphNode.getType(), function (node, ctx) { return ctx.createXmlNode('p', {}); }); litexmlService.registerXMLReader('quote', function (xmlElement, children) { return INodeHelper.createElementNode(QuoteNode.getType(), { children: children }); }); litexmlService.registerXMLReader('p', function (xmlElement, children) { return INodeHelper.createElementNode(ParagraphNode.getType(), { children: children }); }); var headingTags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; headingTags.forEach(function (tag) { litexmlService.registerXMLReader(tag, function (xmlElement, children) { return INodeHelper.createElementNode(HeadingNode.getType(), { children: children, tag: tag }); }); }); } }, { key: "destroy", value: function destroy() { // Cleanup logic _get(_getPrototypeOf(CommonPlugin.prototype), "destroy", this).call(this); } }]); return CommonPlugin; }(KernelPlugin), _defineProperty(_class, "pluginName", 'CommonPlugin'), _class);