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.

312 lines (301 loc) 14.9 kB
var _class; 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 _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 { $isCodeNode } from '@lexical/code'; import { $getNodeByKey, $getSelection, $isRangeSelection, $isTextNode, COLLABORATION_TAG, COMMAND_PRIORITY_CRITICAL, HISTORIC_TAG, KEY_ENTER_COMMAND, PASTE_COMMAND } from 'lexical'; import { KernelPlugin } from "../../../editor-kernel/plugin"; import { createDebugLogger } from "../../../utils/debug"; import { registerMarkdownCommand } from "../command"; import MarkdownDataSource from "../data-source/markdown-data-source"; import { IMarkdownShortCutService, MarkdownShortCutService } from "../service/shortcut"; import { canContainTransformableMarkdown } from "../utils"; import { detectCodeLanguage, detectLanguage } from "../utils/detectLanguage"; export var MarkdownPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) { _inherits(MarkdownPlugin, _KernelPlugin); var _super = _createSuper(MarkdownPlugin); function MarkdownPlugin(kernel, config) { var _this; _classCallCheck(this, MarkdownPlugin); _this = _super.call(this); _defineProperty(_assertThisInitialized(_this), "logger", createDebugLogger('plugin', 'markdown')); _defineProperty(_assertThisInitialized(_this), "service", void 0); _this.kernel = kernel; _this.config = config; _this.service = new MarkdownShortCutService(kernel); kernel.registerService(IMarkdownShortCutService, _this.service); kernel.registerDataSource(new MarkdownDataSource('markdown', _this.service, function (serviceId) { return kernel.requireService(serviceId); })); return _this; } _createClass(MarkdownPlugin, [{ key: "onInit", value: function onInit(editor) { var _this2 = this; this.register(editor.registerUpdateListener(function (_ref) { var tags = _ref.tags, dirtyLeaves = _ref.dirtyLeaves, editorState = _ref.editorState, prevEditorState = _ref.prevEditorState; // Ignore updates from collaboration and undo/redo (as changes already calculated) if (tags.has(COLLABORATION_TAG) || tags.has(HISTORIC_TAG)) { return; } // If editor is still composing (i.e. backticks) we must wait before the user confirms the key if (editor.isComposing()) { return; } var selection = editorState.read($getSelection); var prevSelection = prevEditorState.read($getSelection); // We expect selection to be a collapsed range and not match previous one (as we want // to trigger transforms only as user types) if (!$isRangeSelection(prevSelection) || !$isRangeSelection(selection) || !selection.isCollapsed() || selection.is(prevSelection)) { return; } var anchorKey = selection.anchor.key; var anchorOffset = selection.anchor.offset; var anchorNode = editorState._nodeMap.get(anchorKey); if (!$isTextNode(anchorNode) || !dirtyLeaves.has(anchorKey) || anchorOffset !== 1 && anchorOffset > prevSelection.anchor.offset + 1) { return; } editor.update(function () { if (!canContainTransformableMarkdown(anchorNode)) { return; } var parentNode = anchorNode.getParent(); if (parentNode === null || $isCodeNode(parentNode)) { return; } _this2.service.runTransformers(parentNode, anchorNode, selection.anchor.offset); }); })); this.register(editor.registerCommand(KEY_ENTER_COMMAND, function (payload) { var ret = editor.getEditorState().read(function () { var selection = $getSelection(); if (!$isRangeSelection(selection) || !selection.isCollapsed()) { return false; } var anchorKey = selection.anchor.key; var anchorNode = $getNodeByKey(anchorKey); if (!anchorNode) return false; return { anchorNode: anchorNode, offset: selection.anchor.offset }; }); if (!ret) return false; var anchorNode = ret.anchorNode, offset = ret.offset; if (!canContainTransformableMarkdown(anchorNode)) { return false; } var parentNode = anchorNode.getParent(); if (parentNode === null || $isCodeNode(parentNode)) { return false; } if (_this2.service.testTransformers(parentNode, anchorNode, offset, 'enter')) { queueMicrotask(function () { editor.update(function () { _this2.service.runTransformers(parentNode, anchorNode, offset, 'enter'); }); }); payload === null || payload === void 0 || payload.stopPropagation(); payload === null || payload === void 0 || payload.stopImmediatePropagation(); payload === null || payload === void 0 || payload.preventDefault(); return true; } return false; }, COMMAND_PRIORITY_CRITICAL)); this.register(editor.registerCommand(PASTE_COMMAND, function (event) { if (!(event instanceof ClipboardEvent)) return false; var clipboardData = event.clipboardData; if (!clipboardData) return false; // Get clipboard content and clean BOM/zero-width characters var rawText = clipboardData.getData('text/plain').trimEnd(); // Remove BOM, zero-width spaces, and other invisible characters var text = rawText.replaceAll(/[\u200B-\u200D\u2060\uFEFF]/g, ''); var html = clipboardData.getData('text/html').trimEnd(); // If there's no text content, let Lexical handle it if (!text) return false; _this2.logger.debug('paste content analysis:', { clipboardTypes: Array.from(clipboardData.types || []), hasHTML: !!(html && html.trim()), htmlLength: (html === null || html === void 0 ? void 0 : html.length) || 0, textLength: text.length }); // Check if the pasted plain text contains markdown patterns var hasMarkdownContent = _this2.detectMarkdownContent(text); if (hasMarkdownContent) { // Markdown detected - show confirmation dialog _this2.logger.debug('markdown patterns detected:', _this2.getMarkdownPatterns(text)); var historyState = _this2.kernel.getHistoryState().current; setTimeout(function () { _this2.kernel.emit('markdownParse', { cacheState: editor.getEditorState(), historyState: historyState, markdown: text }); }, 10); } else { // No markdown detected - plain text is already inserted _this2.logger.debug('no markdown patterns detected, keeping as plain text'); } return false; }, COMMAND_PRIORITY_CRITICAL)); this.register(registerMarkdownCommand(editor, this.service, this.kernel.getHistoryState())); } /** * Detect if content is code and should be inserted as code block * Uses advanced language detection with pattern matching * Excludes markdown as it should be handled by markdown formatting dialog */ }, { key: "detectCodeContent", value: function detectCodeContent(text) { // Use the advanced language detector var detected = detectLanguage(text); if (detected && detected.confidence > 50) { // Don't insert markdown as code block - it should trigger the formatting dialog if (detected.language === 'markdown') { return null; } this.logger.debug('language detected:', detected); return detected; } // Fallback to fast detection for common formats var fastDetected = detectCodeLanguage(text); if (fastDetected) { // Don't insert markdown as code block if (fastDetected === 'markdown') { return null; } return { confidence: 80, language: fastDetected }; } return null; } /** * Detect if text contains markdown patterns * Returns false if content is likely code (will be handled by detectCodeContent) */ }, { key: "detectMarkdownContent", value: function detectMarkdownContent(text) { // If code is detected, don't treat as markdown if (this.detectCodeContent(text)) { return false; } var markdownPatterns = [ // Headers /^#{1,6}\s+/m, // Bold/italic /\*{1,2}[^*]+\*{1,2}/, /__?[^_]+__?/, // Code blocks /```[\S\s]*```/, // Inline code /`[^`]+`/, // Links /\[[^\]]*]\([^)]+\)/, // Images /!\[[^\]]*]\([^)]+\)/, // Lists /^[*+-]\s+/m, /^\d+\.\s+/m, // Blockquotes /^>\s+/m, // Tables /\|.*\|.*\|/, // Horizontal rules /^---+$/m, /^\*\*\*+$/m, // Strikethrough /~~[^~]+~~/]; return markdownPatterns.some(function (pattern) { return pattern.test(text); }); } /** * Get specific markdown patterns found in text */ }, { key: "getMarkdownPatterns", value: function getMarkdownPatterns(text) { var patterns = [{ name: 'headers', regex: /^#{1,6}\s+/m }, { name: 'bold', regex: /\*{2}[^*]+\*{2}/ }, { name: 'italic', regex: /\*[^*]+\*/ }, { name: 'code-blocks', regex: /```[\S\s]*```/ }, { name: 'inline-code', regex: /`[^`]+`/ }, { name: 'links', regex: /\[[^\]]*]\([^)]+\)/ }, { name: 'images', regex: /!\[[^\]]*]\([^)]+\)/ }, { name: 'lists', regex: /^[*+-]\s+/m }, { name: 'ordered-lists', regex: /^\d+\.\s+/m }, { name: 'blockquotes', regex: /^>\s+/m }, { name: 'tables', regex: /\|.*\|.*\|/ }, { name: 'horizontal-rules', regex: /^---+$/m }, { name: 'strikethrough', regex: /~~[^~]+~~/ }]; return patterns.filter(function (_ref2) { var regex = _ref2.regex; return regex.test(text); }).map(function (_ref3) { var name = _ref3.name; return name; }); } // /** // * Handle markdown paste by parsing and inserting as structured content // */ // private handleMarkdownPaste(editor: LexicalEditor, text: string): boolean { // try { // // Use the markdown data source to parse the content // const root = parseMarkdownToLexical(text, this.service.markdownReaders); // const selection = $getSelection(); // const nodes = $generateNodesFromSerializedNodes(root.children); // $insertGeneratedNodes(editor, nodes, selection!); // return true; // } catch (error) { // this.logger.error('Failed to handle markdown paste:', error); // } // return false; // } }]); return MarkdownPlugin; }(KernelPlugin), _defineProperty(_class, "pluginName", 'MarkdownPlugin'), _class);