onchain-lexical-markdown 0.0.1

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.
@@ -0,0 +1,529 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ */
8
+
9
+ import type {
10
+ ElementTransformer,
11
+ MultilineElementTransformer,
12
+ TextFormatTransformer,
13
+ TextMatchTransformer,
14
+ Transformer,
15
+ } from './MarkdownTransformers';
16
+ import type {ElementNode, LexicalEditor, TextNode} from 'lexical';
17
+
18
+ import {$isCodeNode} from '@lexical/code';
19
+ import {
20
+ $createRangeSelection,
21
+ $getSelection,
22
+ $isLineBreakNode,
23
+ $isRangeSelection,
24
+ $isRootOrShadowRoot,
25
+ $isTextNode,
26
+ $setSelection,
27
+ COLLABORATION_TAG,
28
+ HISTORIC_TAG,
29
+ } from 'lexical';
30
+ import invariant from 'shared/invariant';
31
+
32
+ import {TRANSFORMERS} from '.';
33
+ import {canContainTransformableMarkdown} from './importTextTransformers';
34
+ import {indexBy, PUNCTUATION_OR_SPACE, transformersByType} from './utils';
35
+
36
+ function runElementTransformers(
37
+ parentNode: ElementNode,
38
+ anchorNode: TextNode,
39
+ anchorOffset: number,
40
+ elementTransformers: ReadonlyArray<ElementTransformer>,
41
+ ): boolean {
42
+ const grandParentNode = parentNode.getParent();
43
+
44
+ if (
45
+ !$isRootOrShadowRoot(grandParentNode) ||
46
+ parentNode.getFirstChild() !== anchorNode
47
+ ) {
48
+ return false;
49
+ }
50
+
51
+ const textContent = anchorNode.getTextContent();
52
+
53
+ // Checking for anchorOffset position to prevent any checks for cases when caret is too far
54
+ // from a line start to be a part of block-level markdown trigger.
55
+ //
56
+ // TODO:
57
+ // Can have a quick check if caret is close enough to the beginning of the string (e.g. offset less than 10-20)
58
+ // since otherwise it won't be a markdown shortcut, but tables are exception
59
+ if (textContent[anchorOffset - 1] !== ' ') {
60
+ return false;
61
+ }
62
+
63
+ for (const {regExp, replace} of elementTransformers) {
64
+ const match = textContent.match(regExp);
65
+
66
+ if (
67
+ match &&
68
+ match[0].length ===
69
+ (match[0].endsWith(' ') ? anchorOffset : anchorOffset - 1)
70
+ ) {
71
+ const nextSiblings = anchorNode.getNextSiblings();
72
+ const [leadingNode, remainderNode] = anchorNode.splitText(anchorOffset);
73
+ leadingNode.remove();
74
+ const siblings = remainderNode
75
+ ? [remainderNode, ...nextSiblings]
76
+ : nextSiblings;
77
+ if (replace(parentNode, siblings, match, false) !== false) {
78
+ return true;
79
+ }
80
+ }
81
+ }
82
+
83
+ return false;
84
+ }
85
+
86
+ function runMultilineElementTransformers(
87
+ parentNode: ElementNode,
88
+ anchorNode: TextNode,
89
+ anchorOffset: number,
90
+ elementTransformers: ReadonlyArray<MultilineElementTransformer>,
91
+ ): boolean {
92
+ const grandParentNode = parentNode.getParent();
93
+
94
+ if (
95
+ !$isRootOrShadowRoot(grandParentNode) ||
96
+ parentNode.getFirstChild() !== anchorNode
97
+ ) {
98
+ return false;
99
+ }
100
+
101
+ const textContent = anchorNode.getTextContent();
102
+
103
+ // Checking for anchorOffset position to prevent any checks for cases when caret is too far
104
+ // from a line start to be a part of block-level markdown trigger.
105
+ //
106
+ // TODO:
107
+ // Can have a quick check if caret is close enough to the beginning of the string (e.g. offset less than 10-20)
108
+ // since otherwise it won't be a markdown shortcut, but tables are exception
109
+ if (textContent[anchorOffset - 1] !== ' ') {
110
+ return false;
111
+ }
112
+
113
+ for (const {regExpStart, replace, regExpEnd} of elementTransformers) {
114
+ if (
115
+ (regExpEnd && !('optional' in regExpEnd)) ||
116
+ (regExpEnd && 'optional' in regExpEnd && !regExpEnd.optional)
117
+ ) {
118
+ continue;
119
+ }
120
+
121
+ const match = textContent.match(regExpStart);
122
+
123
+ if (
124
+ match &&
125
+ match[0].length ===
126
+ (match[0].endsWith(' ') ? anchorOffset : anchorOffset - 1)
127
+ ) {
128
+ const nextSiblings = anchorNode.getNextSiblings();
129
+ const [leadingNode, remainderNode] = anchorNode.splitText(anchorOffset);
130
+ leadingNode.remove();
131
+ const siblings = remainderNode
132
+ ? [remainderNode, ...nextSiblings]
133
+ : nextSiblings;
134
+
135
+ if (replace(parentNode, siblings, match, null, null, false) !== false) {
136
+ return true;
137
+ }
138
+ }
139
+ }
140
+
141
+ return false;
142
+ }
143
+
144
+ function runTextMatchTransformers(
145
+ anchorNode: TextNode,
146
+ anchorOffset: number,
147
+ transformersByTrigger: Readonly<Record<string, Array<TextMatchTransformer>>>,
148
+ ): boolean {
149
+ let textContent = anchorNode.getTextContent();
150
+ const lastChar = textContent[anchorOffset - 1];
151
+ const transformers = transformersByTrigger[lastChar];
152
+
153
+ if (transformers == null) {
154
+ return false;
155
+ }
156
+
157
+ // If typing in the middle of content, remove the tail to do
158
+ // reg exp match up to a string end (caret position)
159
+ if (anchorOffset < textContent.length) {
160
+ textContent = textContent.slice(0, anchorOffset);
161
+ }
162
+
163
+ for (const transformer of transformers) {
164
+ if (!transformer.replace || !transformer.regExp) {
165
+ continue;
166
+ }
167
+ const match = textContent.match(transformer.regExp);
168
+
169
+ if (match === null) {
170
+ continue;
171
+ }
172
+
173
+ const startIndex = match.index || 0;
174
+ const endIndex = startIndex + match[0].length;
175
+ let replaceNode;
176
+
177
+ if (startIndex === 0) {
178
+ [replaceNode] = anchorNode.splitText(endIndex);
179
+ } else {
180
+ [, replaceNode] = anchorNode.splitText(startIndex, endIndex);
181
+ }
182
+
183
+ replaceNode.selectNext(0, 0);
184
+ transformer.replace(replaceNode, match);
185
+ return true;
186
+ }
187
+
188
+ return false;
189
+ }
190
+
191
+ function $runTextFormatTransformers(
192
+ anchorNode: TextNode,
193
+ anchorOffset: number,
194
+ textFormatTransformers: Readonly<
195
+ Record<string, ReadonlyArray<TextFormatTransformer>>
196
+ >,
197
+ ): boolean {
198
+ const textContent = anchorNode.getTextContent();
199
+ const closeTagEndIndex = anchorOffset - 1;
200
+ const closeChar = textContent[closeTagEndIndex];
201
+ // Quick check if we're possibly at the end of inline markdown style
202
+ const matchers = textFormatTransformers[closeChar];
203
+
204
+ if (!matchers) {
205
+ return false;
206
+ }
207
+
208
+ for (const matcher of matchers) {
209
+ const {tag} = matcher;
210
+ const tagLength = tag.length;
211
+ const closeTagStartIndex = closeTagEndIndex - tagLength + 1;
212
+
213
+ // If tag is not single char check if rest of it matches with text content
214
+ if (tagLength > 1) {
215
+ if (
216
+ !isEqualSubString(textContent, closeTagStartIndex, tag, 0, tagLength)
217
+ ) {
218
+ continue;
219
+ }
220
+ }
221
+
222
+ // Space before closing tag cancels inline markdown
223
+ if (textContent[closeTagStartIndex - 1] === ' ') {
224
+ continue;
225
+ }
226
+
227
+ // Some tags can not be used within words, hence should have newline/space/punctuation after it
228
+ const afterCloseTagChar = textContent[closeTagEndIndex + 1];
229
+
230
+ if (
231
+ matcher.intraword === false &&
232
+ afterCloseTagChar &&
233
+ !PUNCTUATION_OR_SPACE.test(afterCloseTagChar)
234
+ ) {
235
+ continue;
236
+ }
237
+
238
+ const closeNode = anchorNode;
239
+ let openNode = closeNode;
240
+ let openTagStartIndex = getOpenTagStartIndex(
241
+ textContent,
242
+ closeTagStartIndex,
243
+ tag,
244
+ );
245
+
246
+ // Go through text node siblings and search for opening tag
247
+ // if haven't found it within the same text node as closing tag
248
+ let sibling: TextNode | null = openNode;
249
+
250
+ while (
251
+ openTagStartIndex < 0 &&
252
+ (sibling = sibling.getPreviousSibling<TextNode>())
253
+ ) {
254
+ if ($isLineBreakNode(sibling)) {
255
+ break;
256
+ }
257
+
258
+ if ($isTextNode(sibling)) {
259
+ if (sibling.hasFormat('code')) {
260
+ continue;
261
+ }
262
+ const siblingTextContent = sibling.getTextContent();
263
+ openNode = sibling;
264
+ openTagStartIndex = getOpenTagStartIndex(
265
+ siblingTextContent,
266
+ siblingTextContent.length,
267
+ tag,
268
+ );
269
+ }
270
+ }
271
+
272
+ // Opening tag is not found
273
+ if (openTagStartIndex < 0) {
274
+ continue;
275
+ }
276
+
277
+ // No content between opening and closing tag
278
+ if (
279
+ openNode === closeNode &&
280
+ openTagStartIndex + tagLength === closeTagStartIndex
281
+ ) {
282
+ continue;
283
+ }
284
+
285
+ // Checking longer tags for repeating chars (e.g. *** vs **)
286
+ const prevOpenNodeText = openNode.getTextContent();
287
+
288
+ if (
289
+ openTagStartIndex > 0 &&
290
+ prevOpenNodeText[openTagStartIndex - 1] === closeChar
291
+ ) {
292
+ continue;
293
+ }
294
+
295
+ // Some tags can not be used within words, hence should have newline/space/punctuation before it
296
+ const beforeOpenTagChar = prevOpenNodeText[openTagStartIndex - 1];
297
+
298
+ if (
299
+ matcher.intraword === false &&
300
+ beforeOpenTagChar &&
301
+ !PUNCTUATION_OR_SPACE.test(beforeOpenTagChar)
302
+ ) {
303
+ continue;
304
+ }
305
+
306
+ // Clean text from opening and closing tags (starting from closing tag
307
+ // to prevent any offset shifts if we start from opening one)
308
+ const prevCloseNodeText = closeNode.getTextContent();
309
+ const closeNodeText =
310
+ prevCloseNodeText.slice(0, closeTagStartIndex) +
311
+ prevCloseNodeText.slice(closeTagEndIndex + 1);
312
+ closeNode.setTextContent(closeNodeText);
313
+ const openNodeText =
314
+ openNode === closeNode ? closeNodeText : prevOpenNodeText;
315
+ openNode.setTextContent(
316
+ openNodeText.slice(0, openTagStartIndex) +
317
+ openNodeText.slice(openTagStartIndex + tagLength),
318
+ );
319
+ const selection = $getSelection();
320
+ const nextSelection = $createRangeSelection();
321
+ $setSelection(nextSelection);
322
+ // Adjust offset based on deleted chars
323
+ const newOffset =
324
+ closeTagEndIndex - tagLength * (openNode === closeNode ? 2 : 1) + 1;
325
+ nextSelection.anchor.set(openNode.__key, openTagStartIndex, 'text');
326
+ nextSelection.focus.set(closeNode.__key, newOffset, 'text');
327
+
328
+ // Apply formatting to selected text
329
+ for (const format of matcher.format) {
330
+ if (!nextSelection.hasFormat(format)) {
331
+ nextSelection.formatText(format);
332
+ }
333
+ }
334
+
335
+ // Collapse selection up to the focus point
336
+ nextSelection.anchor.set(
337
+ nextSelection.focus.key,
338
+ nextSelection.focus.offset,
339
+ nextSelection.focus.type,
340
+ );
341
+
342
+ // Remove formatting from collapsed selection
343
+ for (const format of matcher.format) {
344
+ if (nextSelection.hasFormat(format)) {
345
+ nextSelection.toggleFormat(format);
346
+ }
347
+ }
348
+
349
+ if ($isRangeSelection(selection)) {
350
+ nextSelection.format = selection.format;
351
+ }
352
+
353
+ return true;
354
+ }
355
+
356
+ return false;
357
+ }
358
+
359
+ function getOpenTagStartIndex(
360
+ string: string,
361
+ maxIndex: number,
362
+ tag: string,
363
+ ): number {
364
+ const tagLength = tag.length;
365
+
366
+ for (let i = maxIndex; i >= tagLength; i--) {
367
+ const startIndex = i - tagLength;
368
+
369
+ if (
370
+ isEqualSubString(string, startIndex, tag, 0, tagLength) && // Space after opening tag cancels transformation
371
+ string[startIndex + tagLength] !== ' '
372
+ ) {
373
+ return startIndex;
374
+ }
375
+ }
376
+
377
+ return -1;
378
+ }
379
+
380
+ function isEqualSubString(
381
+ stringA: string,
382
+ aStart: number,
383
+ stringB: string,
384
+ bStart: number,
385
+ length: number,
386
+ ): boolean {
387
+ for (let i = 0; i < length; i++) {
388
+ if (stringA[aStart + i] !== stringB[bStart + i]) {
389
+ return false;
390
+ }
391
+ }
392
+
393
+ return true;
394
+ }
395
+
396
+ export function registerMarkdownShortcuts(
397
+ editor: LexicalEditor,
398
+ transformers: Array<Transformer> = TRANSFORMERS,
399
+ ): () => void {
400
+ const byType = transformersByType(transformers);
401
+ const textFormatTransformersByTrigger = indexBy(
402
+ byType.textFormat,
403
+ ({tag}) => tag[tag.length - 1],
404
+ );
405
+ const textMatchTransformersByTrigger = indexBy(
406
+ byType.textMatch,
407
+ ({trigger}) => trigger,
408
+ );
409
+
410
+ for (const transformer of transformers) {
411
+ const type = transformer.type;
412
+ if (
413
+ type === 'element' ||
414
+ type === 'text-match' ||
415
+ type === 'multiline-element'
416
+ ) {
417
+ const dependencies = transformer.dependencies;
418
+ for (const node of dependencies) {
419
+ if (!editor.hasNode(node)) {
420
+ invariant(
421
+ false,
422
+ 'MarkdownShortcuts: missing dependency %s for transformer. Ensure node dependency is included in editor initial config.',
423
+ node.getType(),
424
+ );
425
+ }
426
+ }
427
+ }
428
+ }
429
+
430
+ const $transform = (
431
+ parentNode: ElementNode,
432
+ anchorNode: TextNode,
433
+ anchorOffset: number,
434
+ ) => {
435
+ // [TODO] 数据转换
436
+ if (
437
+ runElementTransformers(
438
+ parentNode,
439
+ anchorNode,
440
+ anchorOffset,
441
+ byType.element,
442
+ )
443
+ ) {
444
+ return;
445
+ }
446
+
447
+ if (
448
+ runMultilineElementTransformers(
449
+ parentNode,
450
+ anchorNode,
451
+ anchorOffset,
452
+ byType.multilineElement,
453
+ )
454
+ ) {
455
+ return;
456
+ }
457
+
458
+ if (
459
+ runTextMatchTransformers(
460
+ anchorNode,
461
+ anchorOffset,
462
+ textMatchTransformersByTrigger,
463
+ )
464
+ ) {
465
+ return;
466
+ }
467
+
468
+ $runTextFormatTransformers(
469
+ anchorNode,
470
+ anchorOffset,
471
+ textFormatTransformersByTrigger,
472
+ );
473
+ };
474
+
475
+ return editor.registerUpdateListener(
476
+ ({tags, dirtyLeaves, editorState, prevEditorState}) => {
477
+ // Ignore updates from collaboration and undo/redo (as changes already calculated)
478
+ if (tags.has(COLLABORATION_TAG) || tags.has(HISTORIC_TAG)) {
479
+ return;
480
+ }
481
+
482
+ // If editor is still composing (i.e. backticks) we must wait before the user confirms the key
483
+ if (editor.isComposing()) {
484
+ return;
485
+ }
486
+
487
+ const selection = editorState.read($getSelection);
488
+ const prevSelection = prevEditorState.read($getSelection);
489
+
490
+ // We expect selection to be a collapsed range and not match previous one (as we want
491
+ // to trigger transforms only as user types)
492
+ if (
493
+ !$isRangeSelection(prevSelection) ||
494
+ !$isRangeSelection(selection) ||
495
+ !selection.isCollapsed() ||
496
+ selection.is(prevSelection)
497
+ ) {
498
+ return;
499
+ }
500
+
501
+ const anchorKey = selection.anchor.key;
502
+ const anchorOffset = selection.anchor.offset;
503
+
504
+ const anchorNode = editorState._nodeMap.get(anchorKey);
505
+
506
+ if (
507
+ !$isTextNode(anchorNode) ||
508
+ !dirtyLeaves.has(anchorKey) ||
509
+ (anchorOffset !== 1 && anchorOffset > prevSelection.anchor.offset + 1)
510
+ ) {
511
+ return;
512
+ }
513
+
514
+ editor.update(() => {
515
+ if (!canContainTransformableMarkdown(anchorNode)) {
516
+ return;
517
+ }
518
+
519
+ const parentNode = anchorNode.getParent();
520
+
521
+ if (parentNode === null || $isCodeNode(parentNode)) {
522
+ return;
523
+ }
524
+
525
+ $transform(parentNode, anchorNode, selection.anchor.offset);
526
+ });
527
+ },
528
+ );
529
+ }