@lobehub/editor
Version:
A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.
185 lines (172 loc) • 12.7 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 _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 _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 { $createTextNode, $getSelection, $isRangeSelection, COMMAND_PRIORITY_NORMAL, PASTE_COMMAND } from 'lexical';
import { INodeHelper } from "../../../editor-kernel/inode/helper";
import { KernelPlugin } from "../../../editor-kernel/plugin";
import { IMarkdownShortCutService, MARKDOWN_READER_LEVEL_HIGH } from "../../markdown/service/shortcut";
import { createDebugLogger } from "../../../utils/debug";
import { registerLinkHighlightCommand } from "../command";
import { $createLinkHighlightNode, LinkHighlightNode } from "../node/link-highlight";
import { isValidUrl } from "../utils";
import { registerLinkHighlight } from "./registry";
export var LinkHighlightPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
_inherits(LinkHighlightPlugin, _KernelPlugin);
var _super = _createSuper(LinkHighlightPlugin);
function LinkHighlightPlugin(kernel, config) {
var _this;
_classCallCheck(this, LinkHighlightPlugin);
_this = _super.call(this);
_defineProperty(_assertThisInitialized(_this), "logger", createDebugLogger('plugin', 'link-highlight'));
_defineProperty(_assertThisInitialized(_this), "urlRegex", void 0);
_this.kernel = kernel;
_this.config = config;
kernel.registerNodes([LinkHighlightNode]);
kernel.registerThemes({
linkHighlight: (config === null || config === void 0 ? void 0 : config.theme) || 'editor-link-highlight'
});
// Default URL regex that matches http(s), mailto, tel, etc.
_this.urlRegex = (config === null || config === void 0 ? void 0 : config.urlRegex) || /^(?:https?:\/\/|mailto:|tel:)[^\s"<>[\\\]^`{|}]+|^www\.[^\s"<>[\\\]^`{|}]+/i;
_this.logger.debug('LinkHighlightPlugin initialized');
return _this;
}
_createClass(LinkHighlightPlugin, [{
key: "onInit",
value: function onInit(editor) {
var _this$config,
_this$config2,
_this2 = this;
this.register(registerLinkHighlightCommand(editor));
this.register(registerLinkHighlight(editor, this.kernel, {
enableHotkey: (_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.enableHotkey
}));
// Register paste handler for auto-highlighting URLs
if (((_this$config2 = this.config) === null || _this$config2 === void 0 ? void 0 : _this$config2.enablePasteAutoHighlight) !== false) {
this.register(editor.registerCommand(PASTE_COMMAND, function (payload) {
var clipboardData = payload.clipboardData;
if (clipboardData && clipboardData.types && clipboardData.types.length === 1 && clipboardData.types[0] === 'text/plain') {
var data = clipboardData.getData('text/plain').trim();
// Check if the pasted content is a valid URL
if (_this2.urlRegex.test(data) && isValidUrl(data)) {
payload.stopImmediatePropagation();
payload.preventDefault();
_this2.logger.debug('Auto-highlighting pasted URL:', data);
// Insert LinkHighlightNode directly
editor.update(function () {
var selection = $getSelection();
if ($isRangeSelection(selection)) {
var linkHighlightNode = $createLinkHighlightNode();
var textNode = $createTextNode(data);
linkHighlightNode.append(textNode);
selection.insertNodes([linkHighlightNode]);
}
});
return true;
}
}
return false;
}, COMMAND_PRIORITY_NORMAL));
}
var markdownService = this.kernel.requireService(IMarkdownShortCutService);
if (!markdownService) {
return;
}
// Register markdown writer for <link> format
markdownService.registerMarkdownWriter(LinkHighlightNode.getType(), function (ctx, node) {
ctx.appendLine(node.getTextContent());
return true;
});
// Register markdown shortcut for auto-link syntax: <url>
// Matches URLs wrapped in angle brackets like <https://example.com>
markdownService.registerMarkdownShortCut({
regExp: /<((?:https?:\/\/|mailto:|tel:|www\.)[^\s"<>[\\\]^`{|}]+)>\s?$/,
replace: function replace(textNode, match) {
var _match = _slicedToArray(match, 2),
url = _match[1];
if (!url || !isValidUrl(url)) {
return;
}
_this2.logger.debug('Converting markdown auto-link to LinkHighlightNode:', url);
var linkHighlightNode = $createLinkHighlightNode();
var textNodeContent = $createTextNode(url);
linkHighlightNode.append(textNodeContent);
textNode.replace(linkHighlightNode);
return undefined;
},
trigger: '>',
type: 'text-match'
});
// Register HTML reader to handle <url> syntax that might be parsed as HTML
markdownService.registerMarkdownReader('html', function (node) {
var htmlValue = node.value || '';
// Check if this looks like an auto-link: <url>
var match = htmlValue.match(/^<((?:https?:\/\/|mailto:|tel:|www\.)[^\s"<>[\\\]^`{|}]+)>$/);
if (match) {
var url = match[1].replaceAll(/[\u200B-\u200D\u2060\uFEFF]/g, '');
_this2.logger.debug('Converting HTML auto-link to LinkHighlightNode:', url);
return INodeHelper.createElementNode('linkHighlight', {
children: [INodeHelper.createTextNode(url, {})],
direction: 'ltr',
format: '',
indent: 0,
type: 'linkHighlight',
version: 1
});
}
// Not an auto-link, let other handlers process it
return false;
}, MARKDOWN_READER_LEVEL_HIGH);
// Register markdown reader for 'link' type (auto-links like <url>)
// Use HIGH priority to handle auto-links before standard Link plugin
markdownService.registerMarkdownReader('link', function (node, children) {
// Check if this is an auto-link (URL and text are the same)
var url = node.url || '';
// Check if we have text children
if (!children || children.length === 0) {
return false;
}
// Get text content from children
var textContent = children.filter(function (child) {
return child.type === 'text';
}).map(function (child) {
return child.text || '';
}).join('');
// If text matches URL exactly (auto-link syntax), convert to LinkHighlightNode
if (textContent === url) {
_this2.logger.debug('Converting markdown auto-link to LinkHighlightNode:', url);
return INodeHelper.createElementNode('linkHighlight', {
children: [INodeHelper.createTextNode(url, {})],
direction: 'ltr',
format: '',
indent: 0,
type: 'linkHighlight',
version: 1
});
}
// Otherwise, let standard Link plugin handle it
return false;
}, MARKDOWN_READER_LEVEL_HIGH // High priority to intercept auto-links
);
this.logger.debug('LinkHighlightPlugin initialized with markdown support');
}
}]);
return LinkHighlightPlugin;
}(KernelPlugin), _defineProperty(_class, "pluginName", 'LinkHighlightPlugin'), _class);