@lobehub/editor
Version:
A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.
400 lines (386 loc) • 20.8 kB
JavaScript
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 _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 { $getSelection, $insertNodes, $isRangeSelection, $setSelection, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_HIGH, KEY_ESCAPE_COMMAND, KEY_TAB_COMMAND } from 'lexical';
import { INodeHelper } from "../../../editor-kernel/inode/helper";
import { KernelPlugin } from "../../../editor-kernel/plugin";
import { IMarkdownShortCutService } from "../../markdown";
import { createDebugLogger } from "../../../utils/debug";
import { PlaceholderBlockNode, PlaceholderNode } from "../node/placeholderNode";
export var AutoCompletePlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
_inherits(AutoCompletePlugin, _KernelPlugin);
var _super = _createSuper(AutoCompletePlugin);
function AutoCompletePlugin(kernel, config) {
var _config$delay;
var _this;
_classCallCheck(this, AutoCompletePlugin);
_this = _super.call(this);
_defineProperty(_assertThisInitialized(_this), "logger", createDebugLogger('plugin', 'auto-complete'));
_defineProperty(_assertThisInitialized(_this), "lastCursorPosition", null);
_defineProperty(_assertThisInitialized(_this), "cursorStableTimer", null);
_defineProperty(_assertThisInitialized(_this), "abortController", null);
_defineProperty(_assertThisInitialized(_this), "delay", void 0);
_defineProperty(_assertThisInitialized(_this), "placeholderNodes", []);
_defineProperty(_assertThisInitialized(_this), "currentSuggestion", null);
_defineProperty(_assertThisInitialized(_this), "markdownService", null);
_this.kernel = kernel;
_this.config = config;
_this.delay = (_config$delay = config === null || config === void 0 ? void 0 : config.delay) !== null && _config$delay !== void 0 ? _config$delay : 1000;
kernel.registerNodes([PlaceholderNode, PlaceholderBlockNode]);
if (config !== null && config !== void 0 && config.theme) {
kernel.registerThemes(config === null || config === void 0 ? void 0 : config.theme);
}
return _this;
}
_createClass(AutoCompletePlugin, [{
key: "onInit",
value: function onInit(editor) {
var _this2 = this;
this.markdownService = this.kernel.requireService(IMarkdownShortCutService);
if (!this.markdownService) {
this.logger.error('❌ MarkdownShortCutService is required for AutoCompletePlugin');
return;
}
this.register(editor.registerUpdateListener(function (_ref) {
var editorState = _ref.editorState;
editorState.read(function () {
if (editor.isComposing()) {
return;
}
var selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
_this2.clearTimer();
_this2.clearPlaceholderNodes(editor);
return;
}
var currentPosition = {
key: selection.anchor.key,
offset: selection.anchor.offset,
type: selection.anchor.type
};
// Check if cursor position has changed
if (_this2.hasPositionChanged(currentPosition)) {
_this2.clearTimer();
_this2.clearPlaceholderNodes(editor);
_this2.abortController = new AbortController();
// Start new timer for cursor stability check
_this2.cursorStableTimer = window.setTimeout(function () {
_this2.handleCursorStable(editor, currentPosition);
}, _this2.delay);
}
});
}));
// Register Tab key handler to apply suggestion
this.register(editor.registerCommand(KEY_TAB_COMMAND, function (event) {
if (_this2.currentSuggestion) {
event === null || event === void 0 || event.preventDefault();
_this2.applySuggestion(editor);
return true;
}
return false;
}, COMMAND_PRIORITY_HIGH));
this.register(editor.registerCommand(KEY_ESCAPE_COMMAND, function (event) {
if (_this2.currentSuggestion) {
event === null || event === void 0 || event.preventDefault();
_this2.clearPlaceholderNodes(editor);
_this2.currentSuggestion = null;
return true;
}
return false;
}, COMMAND_PRIORITY_CRITICAL));
// Register text content listener to clear placeholder on any other input
this.register(editor.registerTextContentListener(function () {
// If user types anything while placeholder is visible, clear it
if (_this2.placeholderNodes.length > 0) {
_this2.clearPlaceholderNodes(editor);
}
}));
}
}, {
key: "hasPositionChanged",
value: function hasPositionChanged(currentPosition) {
if (!this.lastCursorPosition) {
return true;
}
return this.lastCursorPosition.key !== currentPosition.key || this.lastCursorPosition.offset !== currentPosition.offset || this.lastCursorPosition.type !== currentPosition.type;
}
}, {
key: "clearTimer",
value: function clearTimer() {
var _this$abortController;
(_this$abortController = this.abortController) === null || _this$abortController === void 0 || _this$abortController.abort('use cancel');
if (this.cursorStableTimer) {
clearTimeout(this.cursorStableTimer);
this.cursorStableTimer = null;
}
}
}, {
key: "handleCursorStable",
value: function handleCursorStable(editor, position) {
var _this3 = this;
editor.getEditorState().read(function () {
var _this3$config;
if (editor.isComposing()) {
return;
}
if (!_this3.abortController || _this3.abortController.signal.aborted) {
return;
}
var selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
return;
}
// Verify cursor is still at the same position
var currentPosition = {
key: selection.anchor.key,
offset: selection.anchor.offset,
type: selection.anchor.type
};
if (!_this3.isSamePosition(position, currentPosition)) {
return;
}
// Avoid duplicate triggers for the same position
if (_this3.lastCursorPosition && _this3.isSamePosition(position, _this3.lastCursorPosition)) {
return;
}
_this3.lastCursorPosition = currentPosition;
// Get context around cursor for auto-complete
var anchorNode = selection.anchor.getNode();
var selectionType = 'unknown';
// Get text before cursor in the entire paragraph
var textRet = _this3.getTextBeforeCursor(selection);
selectionType = anchorNode.getType();
// Trigger auto-complete callback if provided
if ((_this3$config = _this3.config) !== null && _this3$config !== void 0 && _this3$config.onAutoComplete) {
_this3.config.onAutoComplete({
abortSignal: _this3.abortController.signal,
afterText: textRet.textAfter,
editor: _this3.kernel,
input: textRet.textBefore,
selectionType: selectionType
}).then(function (result) {
if (result) {
// Store suggestion and show placeholder
_this3.currentSuggestion = result;
_this3.showPlaceholderNodes(editor, result);
_this3.logger.debug('🔍 Auto-complete triggered:', {
afterText: textRet.textAfter,
input: textRet.textBefore,
position: currentPosition,
result: result,
selectionType: selectionType
});
} else {
_this3.clearPlaceholderNodes(editor);
}
});
}
});
}
}, {
key: "getTextBeforeCursor",
value: function getTextBeforeCursor(selection) {
var ret = {
textAfter: '',
textBefore: ''
};
var anchorNode = selection.anchor.getNode();
var anchorOffset = selection.anchor.offset;
// Find the paragraph or root container
var paragraphNode = anchorNode;
while (paragraphNode && paragraphNode.isInline()) {
var parent = paragraphNode.getParent();
if (!parent) break;
paragraphNode = parent;
}
if (!paragraphNode) {
return ret;
}
this.logger.debug('🔍 Paragraph Node Type:', paragraphNode, anchorNode);
var founded = false;
// Collect all text before cursor in the paragraph
var collectTextBeforeCursor = function collectTextBeforeCursor(node, targetNode, targetOffset) {
if (node === targetNode) {
founded = true;
// We've reached the target node, get text up to the cursor position
if (node.getTextContent) {
var nodeText = node.getTextContent();
return {
text: nodeText.slice(0, targetOffset),
textAfter: nodeText.slice(targetOffset)
};
}
return {
text: '',
textAfter: ''
};
}
var collectedText = '';
var collectedTextAfter = '';
// If this is a text node, collect all its text
if (node.getTextContent && node.getType() === 'text') {
if (founded) {
collectedTextAfter += node.getTextContent();
} else {
collectedText += node.getTextContent();
}
}
// Recursively check children
if (node.getChildren) {
var children = node.getChildren();
var _iterator = _createForOfIteratorHelper(children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
var _result = collectTextBeforeCursor(child, targetNode, targetOffset);
collectedTextAfter += _result.textAfter;
collectedText += _result.text;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
return {
text: collectedText,
textAfter: collectedTextAfter
};
};
var result = collectTextBeforeCursor(paragraphNode, anchorNode, anchorOffset);
return {
textAfter: result.textAfter,
textBefore: result.text
};
}
}, {
key: "showPlaceholderNodes",
value: function showPlaceholderNodes(editor, suggestion) {
var _this4 = this;
// this.clearPlaceholderNodes(editor); // Remove existing placeholder first
editor.update(function () {
var selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
_this4.logger.warn('⚠️ No valid selection for placeholder');
return;
}
if (!_this4.markdownService) {
_this4.logger.warn('⚠️ No valid markdown service for placeholder');
return;
}
var nodes = _this4.markdownService.parseMarkdownToLexical(suggestion);
if (nodes.children[0]) {
var firstChild = nodes.children[0];
// Do something with the first child node
// @ts-expect-error not error
var oldChildren = firstChild.children;
// @ts-expect-error not error
firstChild.children = [{
children: oldChildren,
type: 'PlaceholderInline'
}];
}
for (var i = 1; i < nodes.children.length; i++) {
var child = nodes.children[i];
nodes.children[i] = {
// @ts-expect-error not error
children: [child],
type: 'PlaceholderBlock'
};
}
// 创建标记节点并保存其key
var markerNode = INodeHelper.createTextNode("\u200B"); // 使用零宽空格
nodes.children.push({
// @ts-expect-error not error
children: [markerNode],
name: '',
type: 'PlaceholderInline'
});
var saveSel = selection.clone();
_this4.markdownService.insertIRootNode(editor, nodes, selection);
$setSelection(saveSel);
});
}
}, {
key: "clearPlaceholderNodes",
value: function clearPlaceholderNodes(editor) {
editor.update(function () {
editor.getEditorState()._nodeMap.forEach(function (node) {
var selection = $getSelection();
var clonedSelection = selection ? selection.clone() : null;
if (node.isAttached() && ['PlaceholderBlock', 'PlaceholderInline'].includes(node.getType())) {
if (node.getType() === 'PlaceholderInline' && node.getTextContent().includes("\u200B") && node.getPreviousSibling() === null) {
var _node$getParent;
while (node.getNextSibling()) {
var next = node.getNextSibling();
if (next) {
$insertNodes([next]);
}
}
$setSelection(clonedSelection);
(_node$getParent = node.getParent()) === null || _node$getParent === void 0 || _node$getParent.remove();
return;
}
node.remove();
}
});
});
}
}, {
key: "applySuggestion",
value: function applySuggestion(editor) {
var _this5 = this;
if (!this.currentSuggestion) {
return;
}
var markdown = this.currentSuggestion;
editor.update(function () {
var selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed() || !_this5.markdownService) {
return;
}
editor.getEditorState()._nodeMap.forEach(function (node) {
if (node.isAttached() && ['PlaceholderBlock', 'PlaceholderInline'].includes(node.getType())) {
node.remove();
}
});
var nodes = _this5.markdownService.parseMarkdownToLexical(markdown);
_this5.markdownService.insertIRootNode(editor, nodes, selection);
_this5.clearPlaceholderNodes(editor);
_this5.currentSuggestion = null;
});
}
}, {
key: "isSamePosition",
value: function isSamePosition(pos1, pos2) {
return pos1.key === pos2.key && pos1.offset === pos2.offset && pos1.type === pos2.type;
}
}, {
key: "destroy",
value: function destroy() {
this.clearTimer();
// Note: clearPlaceholderNodes needs editor instance, so it should be called before destroy
this.placeholderNodes = []; // Clear references
_get(_getPrototypeOf(AutoCompletePlugin.prototype), "destroy", this).call(this);
}
}]);
return AutoCompletePlugin;
}(KernelPlugin), _defineProperty(_class, "pluginName", 'AutoCompletePlugin'), _class);