@lobehub/editor 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,7 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.g
13
13
  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; }
14
14
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
15
15
  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); }
16
- import { $setSelection } from 'lexical';
16
+ import { $setSelection, TextNode } from 'lexical';
17
17
  import { INodeHelper } from "../../../editor-kernel/inode/helper";
18
18
  import { KernelPlugin } from "../../../editor-kernel/plugin";
19
19
  import { $createCursorNode, cursorNodeSerialized } from "../../common";
@@ -44,6 +44,11 @@ export var CodePlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
44
44
  this.register(registerCodeInline(editor, this.kernel, {
45
45
  enableHotkey: (_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.enableHotkey
46
46
  }));
47
+ this.register(editor.registerNodeTransform(TextNode, function (node) {
48
+ if (node.hasFormat('code')) {
49
+ node.replace($createCodeNode(node.getTextContent())).insertAfter($createCursorNode());
50
+ }
51
+ }));
47
52
  var markdownService = this.kernel.requireService(IMarkdownShortCutService);
48
53
  if (!markdownService) {
49
54
  return;
@@ -1,4 +1,4 @@
1
- import { IS_BOLD, IS_ITALIC, IS_STRIKETHROUGH, IS_SUBSCRIPT, IS_SUPERSCRIPT } from 'lexical';
1
+ import { IS_BOLD, IS_ITALIC, IS_STRIKETHROUGH, IS_SUBSCRIPT, IS_SUPERSCRIPT, IS_UNDERLINE } from 'lexical';
2
2
  import { INodeHelper } from "../../../editor-kernel/inode/helper";
3
3
  export function registerMDReader(markdownService) {
4
4
  markdownService.registerMarkdownReader('blockquote', function (node, children) {
@@ -56,4 +56,29 @@ export function registerMDReader(markdownService) {
56
56
  return child;
57
57
  });
58
58
  });
59
+ markdownService.registerMarkdownReader('html', function (node, children) {
60
+ if (['<ins>', '<u>'].includes(node.value.toLocaleLowerCase())) {
61
+ return children.map(function (child) {
62
+ if (INodeHelper.isTextNode(child)) {
63
+ child.format = (child.format || 0) | IS_UNDERLINE;
64
+ }
65
+ return child;
66
+ });
67
+ } else if (['<em>'].includes(node.value.toLocaleLowerCase())) {
68
+ return children.map(function (child) {
69
+ if (INodeHelper.isTextNode(child)) {
70
+ child.format = (child.format || 0) | IS_ITALIC;
71
+ }
72
+ return child;
73
+ });
74
+ } else if (['<strong>'].includes(node.value.toLocaleLowerCase())) {
75
+ return children.map(function (child) {
76
+ if (INodeHelper.isTextNode(child)) {
77
+ child.format = (child.format || 0) | IS_BOLD;
78
+ }
79
+ return child;
80
+ });
81
+ }
82
+ return false;
83
+ });
59
84
  }
@@ -1,10 +1,21 @@
1
- import type { PhrasingContent, RootContent } from 'mdast';
1
+ import type { Html, PhrasingContent, Root, RootContent } from 'mdast';
2
2
  import type { IElementNode, INode, IRootNode, ITextNode } from "../../../../editor-kernel/inode";
3
3
  export type MarkdownReadNode = INode | ITextNode | IElementNode;
4
- export type MarkdownNode = RootContent | PhrasingContent;
4
+ export type MarkdownNode = Root | RootContent | PhrasingContent;
5
+ export type MarkdownReaderFunc<K> = (node: Extract<MarkdownNode, {
6
+ type: K;
7
+ }>, children: MarkdownReadNode[], index: number) => MarkdownReadNode | MarkdownReadNode[] | false;
5
8
  export type TransformerRecord = {
6
- [K in MarkdownNode['type']]?: (node: Extract<MarkdownNode, {
7
- type: K;
8
- }>, children: MarkdownReadNode[], index: number) => MarkdownReadNode | MarkdownReadNode[];
9
+ [K in MarkdownNode['type']]?: MarkdownReaderFunc<K> | Array<MarkdownReaderFunc<K>>;
9
10
  };
11
+ export type TransfromerRecordArray = {
12
+ [K in MarkdownNode['type']]?: Array<MarkdownReaderFunc<K>>;
13
+ };
14
+ export interface IHTMLStack {
15
+ children: Array<MarkdownReadNode[] | MarkdownReadNode | null>;
16
+ index: number;
17
+ isEndTag: boolean;
18
+ node: Html;
19
+ tag: string;
20
+ }
10
21
  export declare function parseMarkdownToLexical(markdown: string, markdownReaders?: TransformerRecord): IRootNode;
@@ -1,6 +1,16 @@
1
1
  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); }
2
2
  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; }
3
3
  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; }
4
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
5
+ 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."); }
6
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
7
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
8
+ 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; } } }; }
9
+ 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); }
10
+ 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; }
11
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12
+ 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); } }
13
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
4
14
  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; }
5
15
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
6
16
  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); }
@@ -13,57 +23,166 @@ import remarkSupersub from "./supersub";
13
23
 
14
24
  // 使用条件类型确保类型匹配
15
25
 
16
- function convertMdastToLexical(node, index) {
17
- var markdownReaders = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
26
+ var selfClosingHtmlTags = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
27
+ var MarkdownContext = /*#__PURE__*/function () {
28
+ function MarkdownContext(root) {
29
+ _classCallCheck(this, MarkdownContext);
30
+ _defineProperty(this, "stack", []);
31
+ this.root = root;
32
+ }
33
+ _createClass(MarkdownContext, [{
34
+ key: "push",
35
+ value: function push(html) {
36
+ this.stack.push(html);
37
+ }
38
+ }, {
39
+ key: "isReadingHTML",
40
+ get: function get() {
41
+ return this.stack.length > 0;
42
+ }
43
+ }, {
44
+ key: "last",
45
+ get: function get() {
46
+ return this.stack.at(-1);
47
+ }
48
+ }, {
49
+ key: "pop",
50
+ value: function pop() {
51
+ return this.stack.pop();
52
+ }
53
+ }]);
54
+ return MarkdownContext;
55
+ }();
56
+ function convertMdastToLexical(node, index, ctx) {
57
+ var markdownReaders = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
18
58
  switch (node.type) {
19
- case 'root':
20
- {
21
- return _objectSpread(_objectSpread({}, INodeHelper.createRootNode()), {}, {
22
- children: node.children.map(function (child, index) {
23
- return convertMdastToLexical(child, index, markdownReaders);
24
- }).filter(Boolean).flat()
25
- });
26
- }
27
- case 'paragraph':
28
- {
29
- var paragraph = INodeHelper.createParagraph();
30
- return _objectSpread(_objectSpread({}, paragraph), {}, {
31
- children: node.children.map(function (child, index) {
32
- return convertMdastToLexical(child, index, markdownReaders);
33
- }).filter(Boolean).flat()
34
- });
35
- }
36
- case 'heading':
37
- {
38
- // Create heading based on depth (h1-h6)
39
- var headingType = "h".concat(Math.min(Math.max(node.depth, 1), 6));
40
- return INodeHelper.createElementNode('heading', {
41
- children: node.children.map(function (child, index) {
42
- return convertMdastToLexical(child, index, markdownReaders);
43
- }).filter(Boolean).flat(),
44
- direction: 'ltr',
45
- format: '',
46
- indent: 0,
47
- tag: headingType
48
- });
49
- }
50
59
  case 'text':
51
60
  {
52
- return INodeHelper.createTextNode(node.value);
61
+ var textNode = INodeHelper.createTextNode(node.value);
62
+ return textNode;
53
63
  }
54
64
  default:
55
65
  {
56
66
  if (markdownReaders[node.type]) {
57
- var _markdownReaders$node;
58
67
  var _children = [];
59
68
  if ('children' in node && Array.isArray(node.children)) {
60
- _children = node.children.map(function (child, index) {
61
- return convertMdastToLexical(child, index, markdownReaders);
62
- }).filter(Boolean).flat();
69
+ var htmlStack = []; // 当前循环是否包含 HTML 标签
70
+ _children = node.children.reduce(function (ret, child, index) {
71
+ if (child.type === 'html') {
72
+ var tag = child.value.replaceAll(/^<\/?|>$/g, '');
73
+ var isEndTag = child.value.startsWith('</');
74
+ if (selfClosingHtmlTags.has(tag)) {
75
+ // Self-closing tag
76
+ var _reader = markdownReaders['html'];
77
+ if (Array.isArray(_reader)) {
78
+ var _iterator = _createForOfIteratorHelper(_reader),
79
+ _step;
80
+ try {
81
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
82
+ var element = _step.value;
83
+ var inode = element(child, [], index);
84
+ if (inode) {
85
+ ret.push(inode);
86
+ return ret;
87
+ }
88
+ }
89
+ } catch (err) {
90
+ _iterator.e(err);
91
+ } finally {
92
+ _iterator.f();
93
+ }
94
+ } else if (typeof _reader === 'function') {
95
+ var _inode = _reader(child, [], index);
96
+ if (_inode) {
97
+ ret.push(_inode);
98
+ return ret;
99
+ }
100
+ }
101
+ return ret;
102
+ }
103
+ if (isEndTag) {
104
+ var top = ctx.pop();
105
+ htmlStack.pop();
106
+ if ((top === null || top === void 0 ? void 0 : top.tag) !== tag) {
107
+ logger.warn('HTML tag mismatch:', tag);
108
+ ret.push.apply(ret, _toConsumableArray((top === null || top === void 0 ? void 0 : top.children) || []));
109
+ return ret;
110
+ }
111
+ var _reader2 = markdownReaders['html'];
112
+ var _children2 = top.children.flat().filter(Boolean) || [];
113
+ if (Array.isArray(_reader2)) {
114
+ var _iterator2 = _createForOfIteratorHelper(_reader2),
115
+ _step2;
116
+ try {
117
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
118
+ var _element = _step2.value;
119
+ var _inode2 = _element(top.node, _children2, index);
120
+ if (_inode2) {
121
+ ret.push(_inode2);
122
+ return ret;
123
+ }
124
+ }
125
+ } catch (err) {
126
+ _iterator2.e(err);
127
+ } finally {
128
+ _iterator2.f();
129
+ }
130
+ } else if (typeof _reader2 === 'function') {
131
+ var _inode3 = _reader2(top.node, _children2, index);
132
+ if (_inode3) {
133
+ ret.push(_inode3);
134
+ return ret;
135
+ }
136
+ }
137
+ if (top) {
138
+ ret.push.apply(ret, _toConsumableArray(top.children));
139
+ }
140
+ return ret;
141
+ }
142
+ var htmlStackItem = {
143
+ children: [],
144
+ index: index,
145
+ isEndTag: isEndTag,
146
+ node: child,
147
+ tag: tag
148
+ };
149
+ htmlStack.push(htmlStackItem);
150
+ ctx.push(htmlStackItem);
151
+ return ret;
152
+ }
153
+ if (htmlStack.length > 0) {
154
+ var _top = ctx.last;
155
+ if (_top) {
156
+ _top.children.push(convertMdastToLexical(child, index, ctx, markdownReaders));
157
+ }
158
+ return ret;
159
+ }
160
+ ret.push(convertMdastToLexical(child, index, ctx, markdownReaders));
161
+ return ret;
162
+ }, []).filter(Boolean).flat();
63
163
  }
64
- var inode = (_markdownReaders$node = markdownReaders[node.type]) === null || _markdownReaders$node === void 0 ? void 0 : _markdownReaders$node.call(markdownReaders, node, _children, index);
65
- if (inode) {
66
- return inode;
164
+ var reader = markdownReaders[node.type];
165
+ if (Array.isArray(reader)) {
166
+ var _iterator3 = _createForOfIteratorHelper(reader),
167
+ _step3;
168
+ try {
169
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
170
+ var element = _step3.value;
171
+ var inode = element(node, _children, index);
172
+ if (inode) {
173
+ return inode;
174
+ }
175
+ }
176
+ } catch (err) {
177
+ _iterator3.e(err);
178
+ } finally {
179
+ _iterator3.f();
180
+ }
181
+ } else if (typeof reader === 'function') {
182
+ var _inode4 = reader(node, _children, index);
183
+ if (_inode4) {
184
+ return _inode4;
185
+ }
67
186
  }
68
187
  }
69
188
 
@@ -72,11 +191,41 @@ function convertMdastToLexical(node, index) {
72
191
  }
73
192
  }
74
193
  }
194
+ function registerDefaultReaders(markdownReaders) {
195
+ if (!markdownReaders['root']) {
196
+ markdownReaders['root'] = function (node, children) {
197
+ return _objectSpread(_objectSpread({}, INodeHelper.createRootNode()), {}, {
198
+ children: children
199
+ });
200
+ };
201
+ }
202
+ if (!markdownReaders['paragraph']) {
203
+ markdownReaders['paragraph'] = function (node, children) {
204
+ return _objectSpread(_objectSpread({}, INodeHelper.createParagraph()), {}, {
205
+ children: children
206
+ });
207
+ };
208
+ }
209
+ if (!markdownReaders['heading']) {
210
+ markdownReaders['heading'] = function (node, children) {
211
+ var headingType = "h".concat(Math.min(Math.max(node.depth, 1), 6));
212
+ return INodeHelper.createElementNode('heading', {
213
+ children: children,
214
+ direction: 'ltr',
215
+ format: '',
216
+ indent: 0,
217
+ tag: headingType
218
+ });
219
+ };
220
+ }
221
+ }
75
222
  export function parseMarkdownToLexical(markdown) {
76
223
  var markdownReaders = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
77
224
  var ast = remark().use(remarkMath).use(remarkSupersub).use([[remarkGfm, {
78
225
  singleTilde: false
79
226
  }]]).parse(markdown);
80
227
  logger.debug('Parsed MDAST:', ast);
81
- return convertMdastToLexical(ast, 0, markdownReaders);
228
+ var ctx = new MarkdownContext(ast);
229
+ registerDefaultReaders(markdownReaders);
230
+ return convertMdastToLexical(ast, 0, ctx, markdownReaders);
82
231
  }
@@ -1,3 +1,4 @@
1
1
  export { MarkdownPlugin } from './plugin';
2
- export { IMarkdownShortCutService } from './service/shortcut';
2
+ export type { MARKDOWN_READER_LEVEL } from './service/shortcut';
3
+ export { IMarkdownShortCutService, MARKDOWN_READER_LEVEL_HIGH, MARKDOWN_READER_LEVEL_NORMAL, MARKDOWN_WRITER_LEVEL_MAX, } from './service/shortcut';
3
4
  export { isPunctuationChar } from './utils';
@@ -1,3 +1,3 @@
1
1
  export { MarkdownPlugin } from "./plugin";
2
- export { IMarkdownShortCutService } from "./service/shortcut";
2
+ export { IMarkdownShortCutService, MARKDOWN_READER_LEVEL_HIGH, MARKDOWN_READER_LEVEL_NORMAL, MARKDOWN_WRITER_LEVEL_MAX } from "./service/shortcut";
3
3
  export { isPunctuationChar } from "./utils";
@@ -1,6 +1,6 @@
1
1
  import { ElementNode, LexicalNode, TextNode } from 'lexical';
2
2
  import type { IEditorKernel, IServiceID } from "../../../types/kernel";
3
- import type { TransformerRecord } from '../data-source/markdown/parse';
3
+ import type { MarkdownReaderFunc, TransformerRecord, TransfromerRecordArray } from '../data-source/markdown/parse';
4
4
  import type { Transformer } from './transformers';
5
5
  export interface IMarkdownWriterContext {
6
6
  /**
@@ -22,11 +22,15 @@ export interface IMarkdownWriterContext {
22
22
  */
23
23
  wrap: (before: string, after: string) => void;
24
24
  }
25
+ export declare const MARKDOWN_WRITER_LEVEL_MAX = 0;
26
+ export declare const MARKDOWN_READER_LEVEL_HIGH = 1;
27
+ export declare const MARKDOWN_READER_LEVEL_NORMAL = 2;
28
+ export type MARKDOWN_READER_LEVEL = typeof MARKDOWN_READER_LEVEL_HIGH | typeof MARKDOWN_READER_LEVEL_NORMAL | typeof MARKDOWN_WRITER_LEVEL_MAX;
25
29
  export interface IMarkdownShortCutService {
26
30
  /**
27
31
  * Register Markdown reader
28
32
  */
29
- registerMarkdownReader<K extends keyof TransformerRecord>(type: K, reader: TransformerRecord[K]): void;
33
+ registerMarkdownReader<K extends keyof TransformerRecord>(type: K, reader: MarkdownReaderFunc<K>, level?: MARKDOWN_READER_LEVEL): void;
30
34
  registerMarkdownShortCut(transformer: Transformer): void;
31
35
  registerMarkdownShortCuts(transformers: Transformer[]): void;
32
36
  /**
@@ -47,7 +51,7 @@ export declare class MarkdownShortCutService implements IMarkdownShortCutService
47
51
  private _markdownReaders;
48
52
  constructor(kernel?: IEditorKernel | undefined);
49
53
  get markdownWriters(): Record<string, (_ctx: IMarkdownWriterContext, _node: LexicalNode) => boolean | void>;
50
- get markdownReaders(): TransformerRecord;
54
+ get markdownReaders(): TransfromerRecordArray;
51
55
  private _textFormatTransformersByTrigger;
52
56
  private _textMatchTransformersByTrigger;
53
57
  get textMatchTransformersByTrigger(): Readonly<Record<string, Readonly<{
@@ -70,5 +74,5 @@ export declare class MarkdownShortCutService implements IMarkdownShortCutService
70
74
  testTransformers(parentNode: ElementNode, anchorNode: TextNode, anchorOffset: number, trigger?: 'enter'): boolean;
71
75
  runTransformers(parentNode: ElementNode, anchorNode: TextNode, anchorOffset: number, trigger?: 'enter'): boolean;
72
76
  registerMarkdownWriter(type: string, writer: (ctx: IMarkdownWriterContext, node: LexicalNode) => boolean | void): void;
73
- registerMarkdownReader<K extends keyof TransformerRecord>(type: K, reader: TransformerRecord[K]): void;
77
+ registerMarkdownReader<K extends keyof TransformerRecord>(type: K, reader: MarkdownReaderFunc<K>, level?: MARKDOWN_READER_LEVEL): void;
74
78
  }
@@ -1,6 +1,10 @@
1
1
  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); }
2
2
  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; } } }; }
3
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
4
+ 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."); }
3
5
  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); }
6
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
7
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
4
8
  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; }
5
9
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6
10
  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); } }
@@ -15,6 +19,9 @@ import { genServiceId } from "../../../editor-kernel";
15
19
  import { createDebugLogger } from "../../../utils/debug";
16
20
  import { indexBy } from "../utils";
17
21
  import { $runTextFormatTransformers, runElementTransformers, runTextMatchTransformers, testElementTransformers } from "./transformers";
22
+ export var MARKDOWN_WRITER_LEVEL_MAX = 0;
23
+ export var MARKDOWN_READER_LEVEL_HIGH = 1;
24
+ export var MARKDOWN_READER_LEVEL_NORMAL = 2;
18
25
  export var IMarkdownShortCutService = genServiceId('MarkdownShortCutService');
19
26
  export var MarkdownShortCutService = /*#__PURE__*/function () {
20
27
  function MarkdownShortCutService(kernel) {
@@ -24,7 +31,7 @@ export var MarkdownShortCutService = /*#__PURE__*/function () {
24
31
  _defineProperty(this, "textMatchTransformers", []);
25
32
  _defineProperty(this, "logger", createDebugLogger('service', 'markdown'));
26
33
  _defineProperty(this, "_markdownWriters", {});
27
- _defineProperty(this, "_markdownReaders", {});
34
+ _defineProperty(this, "_markdownReaders", [{}, {}, {}]);
28
35
  _defineProperty(this, "_textFormatTransformersByTrigger", null);
29
36
  _defineProperty(this, "_textMatchTransformersByTrigger", null);
30
37
  this.kernel = kernel;
@@ -37,7 +44,18 @@ export var MarkdownShortCutService = /*#__PURE__*/function () {
37
44
  }, {
38
45
  key: "markdownReaders",
39
46
  get: function get() {
40
- return this._markdownReaders;
47
+ return this._markdownReaders.reduce(function (acc, curr) {
48
+ // @ts-expect-error not error
49
+ Object.keys(curr).forEach(function (key) {
50
+ if (!acc[key]) {
51
+ acc[key] = [];
52
+ }
53
+ var existing = acc[key];
54
+ var adding = curr[key];
55
+ existing.push.apply(existing, _toConsumableArray(adding));
56
+ });
57
+ return acc;
58
+ }, {});
41
59
  }
42
60
  }, {
43
61
  key: "textMatchTransformersByTrigger",
@@ -142,17 +160,14 @@ export var MarkdownShortCutService = /*#__PURE__*/function () {
142
160
  }, {
143
161
  key: "registerMarkdownReader",
144
162
  value: function registerMarkdownReader(type, reader) {
145
- var _this$kernel2;
146
- if (!this._markdownReaders[type]) {
147
- this._markdownReaders[type] = reader;
148
- return;
163
+ var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : MARKDOWN_READER_LEVEL_NORMAL;
164
+ if (!this._markdownReaders[level][type]) {
165
+ this._markdownReaders[level][type] = [];
149
166
  }
150
- if ((_this$kernel2 = this.kernel) !== null && _this$kernel2 !== void 0 && _this$kernel2.isHotReloadMode()) {
151
- this.logger.warn("\uD83D\uDD04 Hot reload: markdown reader \"".concat(type, "\""));
152
- this._markdownReaders[type] = reader;
153
- return;
167
+ if (this._markdownReaders[level]) {
168
+ var _this$_markdownReader;
169
+ (_this$_markdownReader = this._markdownReaders[level][type]) === null || _this$_markdownReader === void 0 || _this$_markdownReader.push(reader);
154
170
  }
155
- throw new Error("Markdown reader for type \"".concat(type, "\" is already registered."));
156
171
  }
157
172
  }]);
158
173
  return MarkdownShortCutService;
@@ -1,3 +1,4 @@
1
1
  export { INSERT_MENTION_COMMAND } from './command';
2
+ export type { SerializedMentionNode } from './node/MentionNode';
2
3
  export * from './plugin';
3
4
  export * from './react';
@@ -1,8 +1,11 @@
1
1
  import { LexicalEditor } from 'lexical';
2
+ import { Html } from 'mdast';
3
+ import { INode } from "../../../editor-kernel/inode";
2
4
  import type { IEditorPluginConstructor } from "../../../types";
3
- import { MentionNode } from '../node/MentionNode';
5
+ import { MentionNode, SerializedMentionNode } from '../node/MentionNode';
4
6
  export interface MentionPluginOptions {
5
7
  decorator: (node: MentionNode, editor: LexicalEditor) => any;
8
+ markdownReader?: (node: Html, children: INode[]) => SerializedMentionNode | null | false;
6
9
  markdownWriter?: (file: MentionNode) => string;
7
10
  theme?: {
8
11
  mention?: string;
@@ -14,7 +14,7 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
14
14
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
15
15
  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); }
16
16
  import { KernelPlugin } from "../../../editor-kernel/plugin";
17
- import { IMarkdownShortCutService } from "../../markdown";
17
+ import { IMarkdownShortCutService, MARKDOWN_READER_LEVEL_HIGH } from "../../markdown";
18
18
  import { registerMentionCommand } from "../command";
19
19
  import { $isMentionNode, MentionNode } from "../node/MentionNode";
20
20
  import { registerMentionNodeSelectionObserver } from "./register";
@@ -25,7 +25,6 @@ export var MentionPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
25
25
  _inherits(MentionPlugin, _KernelPlugin);
26
26
  var _super = _createSuper(MentionPlugin);
27
27
  function MentionPlugin(kernel, config) {
28
- var _kernel$requireServic;
29
28
  var _this;
30
29
  _classCallCheck(this, MentionPlugin);
31
30
  _this = _super.call(this);
@@ -39,15 +38,6 @@ export var MentionPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
39
38
  _this.registerDecorator(kernel, MentionNode.getType(), function (node, editor) {
40
39
  return config !== null && config !== void 0 && config.decorator ? config.decorator(node, editor) : null;
41
40
  });
42
- (_kernel$requireServic = kernel.requireService(IMarkdownShortCutService)) === null || _kernel$requireServic === void 0 || _kernel$requireServic.registerMarkdownWriter(MentionNode.getType(), function (ctx, node) {
43
- if ($isMentionNode(node)) {
44
- if (config !== null && config !== void 0 && config.markdownWriter) {
45
- ctx.appendLine(config.markdownWriter(node));
46
- return;
47
- }
48
- ctx.appendLine("".concat(node.label));
49
- }
50
- });
51
41
  return _this;
52
42
  }
53
43
  _createClass(MentionPlugin, [{
@@ -55,6 +45,32 @@ export var MentionPlugin = (_class = /*#__PURE__*/function (_KernelPlugin) {
55
45
  value: function onInit(editor) {
56
46
  this.register(registerMentionCommand(editor));
57
47
  this.register(registerMentionNodeSelectionObserver(editor));
48
+ this.registerMarkdown();
49
+ }
50
+ }, {
51
+ key: "registerMarkdown",
52
+ value: function registerMarkdown() {
53
+ var _this$kernel$requireS,
54
+ _this2 = this,
55
+ _this$config;
56
+ (_this$kernel$requireS = this.kernel.requireService(IMarkdownShortCutService)) === null || _this$kernel$requireS === void 0 || _this$kernel$requireS.registerMarkdownWriter(MentionNode.getType(), function (ctx, node) {
57
+ if ($isMentionNode(node)) {
58
+ var _this2$config;
59
+ if ((_this2$config = _this2.config) !== null && _this2$config !== void 0 && _this2$config.markdownWriter) {
60
+ ctx.appendLine(_this2.config.markdownWriter(node));
61
+ return;
62
+ }
63
+ ctx.appendLine("".concat(node.label));
64
+ }
65
+ });
66
+ if ((_this$config = this.config) !== null && _this$config !== void 0 && _this$config.markdownReader) {
67
+ var _this$kernel$requireS2;
68
+ (_this$kernel$requireS2 = this.kernel.requireService(IMarkdownShortCutService)) === null || _this$kernel$requireS2 === void 0 || _this$kernel$requireS2.registerMarkdownReader('html', function (node, children) {
69
+ var _this2$config2;
70
+ return (_this2$config2 = _this2.config) !== null && _this2$config2 !== void 0 && _this2$config2.markdownReader ? _this2.config.markdownReader(node, children) || false : false;
71
+ // return this.config?.markdownReader ? this.config.markdownReader(node, children) || false : false;
72
+ }, MARKDOWN_READER_LEVEL_HIGH);
73
+ }
58
74
  }
59
75
  }]);
60
76
  return MentionPlugin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/editor",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.",
5
5
  "keywords": [
6
6
  "lobehub",