@react-fabric/lexical 1.0.0-beta.6 → 1.0.0-beta.60

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.
Files changed (76) hide show
  1. package/{src/editor/Lexical.module.css → css/_lexical.css} +8 -4
  2. package/css/styles.css +24 -0
  3. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +62 -20
  4. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.js +1 -1
  5. package/dist/cjs/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +11 -11
  6. package/dist/cjs/node_modules/@lexical/code/LexicalCode.dev.js +643 -245
  7. package/dist/cjs/node_modules/@lexical/code/LexicalCode.js +1 -1
  8. package/dist/cjs/node_modules/@lexical/code/LexicalCode.prod.js +29 -22
  9. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.dev.js +13 -6
  10. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.js +1 -1
  11. package/dist/cjs/node_modules/@lexical/html/LexicalHtml.prod.js +3 -3
  12. package/dist/cjs/node_modules/@lexical/link/LexicalLink.dev.js +242 -141
  13. package/dist/cjs/node_modules/@lexical/link/LexicalLink.js +1 -1
  14. package/dist/cjs/node_modules/@lexical/link/LexicalLink.prod.js +11 -10
  15. package/dist/cjs/node_modules/@lexical/list/LexicalList.dev.js +594 -255
  16. package/dist/cjs/node_modules/@lexical/list/LexicalList.js +1 -1
  17. package/dist/cjs/node_modules/@lexical/list/LexicalList.prod.js +23 -16
  18. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.dev.js +102 -53
  19. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.js +1 -1
  20. package/dist/cjs/node_modules/@lexical/rich-text/LexicalRichText.prod.js +10 -10
  21. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.dev.js +275 -194
  22. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.js +5 -1
  23. package/dist/cjs/node_modules/@lexical/selection/LexicalSelection.prod.js +28 -18
  24. package/dist/cjs/node_modules/@lexical/table/LexicalTable.dev.js +2293 -878
  25. package/dist/cjs/node_modules/@lexical/table/LexicalTable.js +1 -1
  26. package/dist/cjs/node_modules/@lexical/table/LexicalTable.prod.js +53 -40
  27. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.dev.js +471 -193
  28. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.js +13 -1
  29. package/dist/cjs/node_modules/@lexical/utils/LexicalUtils.prod.js +47 -32
  30. package/dist/cjs/node_modules/prismjs/prism.js +1 -1
  31. package/dist/cjs/packages/lexical/src/components/StickyComponent.js +1 -1
  32. package/dist/cjs/packages/lexical/src/editor/LexicalEditor.js +30 -5
  33. package/dist/cjs/packages/lexical/src/hooks/useFormatWatcher.js +86 -83
  34. package/dist/cjs/packages/lexical/src/plugins/ToolbarPlugin.js +25 -17
  35. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.dev.js +62 -20
  36. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.js +1 -1
  37. package/dist/esm/node_modules/@lexical/clipboard/LexicalClipboard.prod.js +3 -3
  38. package/dist/esm/node_modules/@lexical/code/LexicalCode.dev.js +637 -246
  39. package/dist/esm/node_modules/@lexical/code/LexicalCode.js +1 -1
  40. package/dist/esm/node_modules/@lexical/code/LexicalCode.prod.js +4 -4
  41. package/dist/esm/node_modules/@lexical/html/LexicalHtml.dev.js +14 -7
  42. package/dist/esm/node_modules/@lexical/html/LexicalHtml.js +1 -1
  43. package/dist/esm/node_modules/@lexical/html/LexicalHtml.prod.js +3 -3
  44. package/dist/esm/node_modules/@lexical/link/LexicalLink.dev.js +244 -144
  45. package/dist/esm/node_modules/@lexical/link/LexicalLink.js +1 -1
  46. package/dist/esm/node_modules/@lexical/link/LexicalLink.prod.js +4 -4
  47. package/dist/esm/node_modules/@lexical/list/LexicalList.dev.js +590 -257
  48. package/dist/esm/node_modules/@lexical/list/LexicalList.js +1 -1
  49. package/dist/esm/node_modules/@lexical/list/LexicalList.prod.js +5 -4
  50. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.dev.js +104 -55
  51. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.js +1 -1
  52. package/dist/esm/node_modules/@lexical/rich-text/LexicalRichText.prod.js +4 -4
  53. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.dev.js +267 -196
  54. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.js +4 -2
  55. package/dist/esm/node_modules/@lexical/selection/LexicalSelection.prod.js +4 -4
  56. package/dist/esm/node_modules/@lexical/table/LexicalTable.dev.js +2283 -881
  57. package/dist/esm/node_modules/@lexical/table/LexicalTable.js +1 -1
  58. package/dist/esm/node_modules/@lexical/table/LexicalTable.prod.js +4 -4
  59. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.dev.js +457 -194
  60. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.js +8 -2
  61. package/dist/esm/node_modules/@lexical/utils/LexicalUtils.prod.js +3 -3
  62. package/dist/esm/node_modules/prismjs/prism.js +1 -1
  63. package/dist/esm/packages/lexical/src/components/StickyComponent.js +1 -1
  64. package/dist/esm/packages/lexical/src/editor/LexicalEditor.js +30 -5
  65. package/dist/esm/packages/lexical/src/hooks/useFormatWatcher.js +88 -85
  66. package/dist/esm/packages/lexical/src/plugins/ToolbarPlugin.js +25 -17
  67. package/dist/types/editor/LexicalEditor.d.ts +25 -0
  68. package/dist/types/hooks/useFormatWatcher.d.ts +2 -2
  69. package/dist/types/nodes/StickyNode.d.ts +0 -1
  70. package/package.json +14 -13
  71. package/src/components/StickyComponent.tsx +2 -2
  72. package/src/editor/LexicalEditor.tsx +57 -26
  73. package/src/hooks/useFormatWatcher.ts +35 -31
  74. package/src/plugins/ToolbarPlugin.tsx +27 -17
  75. package/dist/cjs/editor/Lexical.module.css +0 -1
  76. package/dist/esm/editor/Lexical.module.css +0 -1
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var LexicalUtils = require('../utils/LexicalUtils.js');
4
+ var lexical = require('lexical');
3
5
  require('../../prismjs/prism.js');
4
6
  require('../../prismjs/components/prism-clike.js');
5
7
  require('../../prismjs/components/prism-javascript.js');
@@ -16,8 +18,6 @@ require('../../prismjs/components/prism-swift.js');
16
18
  require('../../prismjs/components/prism-typescript.js');
17
19
  require('../../prismjs/components/prism-java.js');
18
20
  require('../../prismjs/components/prism-cpp.js');
19
- var LexicalUtils = require('../utils/LexicalUtils.js');
20
- var lexical = require('lexical');
21
21
 
22
22
  /**
23
23
  * Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -36,14 +36,22 @@ var lexical = require('lexical');
36
36
  *
37
37
  */
38
38
 
39
- const isLanguageSupportedByPrism = language => {
40
- try {
41
- // eslint-disable-next-line no-prototype-builtins
42
- return language ? window.Prism.languages.hasOwnProperty(language) : false;
43
- } catch (_unused) {
44
- return false;
45
- }
46
- };
39
+ // Do not require this module directly! Use normal `invariant` calls.
40
+
41
+ function formatDevErrorMessage(message) {
42
+ throw new Error(message);
43
+ }
44
+
45
+ /**
46
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
47
+ *
48
+ * This source code is licensed under the MIT license found in the
49
+ * LICENSE file in the root directory of this source tree.
50
+ *
51
+ */
52
+
53
+ const DEFAULT_CODE_LANGUAGE = 'javascript';
54
+ const getDefaultCodeLanguage = () => DEFAULT_CODE_LANGUAGE;
47
55
  function hasChildDOMNodeTag(node, tagName) {
48
56
  for (const child of node.childNodes) {
49
57
  if (LexicalUtils.isHTMLElement(child) && child.tagName === tagName) {
@@ -55,6 +63,7 @@ function hasChildDOMNodeTag(node, tagName) {
55
63
  }
56
64
  const LANGUAGE_DATA_ATTRIBUTE = 'data-language';
57
65
  const HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE = 'data-highlight-language';
66
+ const THEME_DATA_ATTRIBUTE = 'data-theme';
58
67
 
59
68
  /** @noInheritDoc */
60
69
  class CodeNode extends lexical.ElementNode {
@@ -62,6 +71,8 @@ class CodeNode extends lexical.ElementNode {
62
71
 
63
72
  /** @internal */
64
73
 
74
+ /** @internal */
75
+
65
76
  static getType() {
66
77
  return 'code';
67
78
  }
@@ -70,8 +81,15 @@ class CodeNode extends lexical.ElementNode {
70
81
  }
71
82
  constructor(language, key) {
72
83
  super(key);
73
- this.__language = language;
74
- this.__isSyntaxHighlightSupported = isLanguageSupportedByPrism(language);
84
+ this.__language = language || undefined;
85
+ this.__isSyntaxHighlightSupported = false;
86
+ this.__theme = undefined;
87
+ }
88
+ afterCloneFrom(prevNode) {
89
+ super.afterCloneFrom(prevNode);
90
+ this.__language = prevNode.__language;
91
+ this.__theme = prevNode.__theme;
92
+ this.__isSyntaxHighlightSupported = prevNode.__isSyntaxHighlightSupported;
75
93
  }
76
94
 
77
95
  // View
@@ -86,6 +104,14 @@ class CodeNode extends lexical.ElementNode {
86
104
  element.setAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
87
105
  }
88
106
  }
107
+ const theme = this.getTheme();
108
+ if (theme) {
109
+ element.setAttribute(THEME_DATA_ATTRIBUTE, theme);
110
+ }
111
+ const style = this.getStyle();
112
+ if (style) {
113
+ element.setAttribute('style', style);
114
+ }
89
115
  return element;
90
116
  }
91
117
  updateDOM(prevNode, dom, config) {
@@ -94,15 +120,40 @@ class CodeNode extends lexical.ElementNode {
94
120
  if (language) {
95
121
  if (language !== prevLanguage) {
96
122
  dom.setAttribute(LANGUAGE_DATA_ATTRIBUTE, language);
97
- if (this.__isSyntaxHighlightSupported) {
98
- dom.setAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
99
- }
100
123
  }
101
124
  } else if (prevLanguage) {
102
125
  dom.removeAttribute(LANGUAGE_DATA_ATTRIBUTE);
103
- if (prevNode.__isSyntaxHighlightSupported) {
126
+ }
127
+ const isSyntaxHighlightSupported = this.__isSyntaxHighlightSupported;
128
+ const prevIsSyntaxHighlightSupported = prevNode.__isSyntaxHighlightSupported;
129
+ if (prevIsSyntaxHighlightSupported && prevLanguage) {
130
+ if (isSyntaxHighlightSupported && language) {
131
+ if (language !== prevLanguage) {
132
+ dom.setAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
133
+ }
134
+ } else {
104
135
  dom.removeAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE);
105
136
  }
137
+ } else if (isSyntaxHighlightSupported && language) {
138
+ dom.setAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
139
+ }
140
+ const theme = this.__theme;
141
+ const prevTheme = prevNode.__theme;
142
+ if (theme) {
143
+ if (theme !== prevTheme) {
144
+ dom.setAttribute(THEME_DATA_ATTRIBUTE, theme);
145
+ }
146
+ } else if (prevTheme) {
147
+ dom.removeAttribute(THEME_DATA_ATTRIBUTE);
148
+ }
149
+ const style = this.__style;
150
+ const prevStyle = prevNode.__style;
151
+ if (style) {
152
+ if (style !== prevStyle) {
153
+ dom.setAttribute('style', style);
154
+ }
155
+ } else if (prevStyle) {
156
+ dom.removeAttribute('style');
106
157
  }
107
158
  return false;
108
159
  }
@@ -117,6 +168,14 @@ class CodeNode extends lexical.ElementNode {
117
168
  element.setAttribute(HIGHLIGHT_LANGUAGE_DATA_ATTRIBUTE, language);
118
169
  }
119
170
  }
171
+ const theme = this.getTheme();
172
+ if (theme) {
173
+ element.setAttribute(THEME_DATA_ATTRIBUTE, theme);
174
+ }
175
+ const style = this.getStyle();
176
+ if (style) {
177
+ element.setAttribute('style', style);
178
+ }
120
179
  return {
121
180
  element
122
181
  };
@@ -181,18 +240,16 @@ class CodeNode extends lexical.ElementNode {
181
240
  };
182
241
  }
183
242
  static importJSON(serializedNode) {
184
- const node = $createCodeNode(serializedNode.language);
185
- node.setFormat(serializedNode.format);
186
- node.setIndent(serializedNode.indent);
187
- node.setDirection(serializedNode.direction);
188
- return node;
243
+ return $createCodeNode().updateFromJSON(serializedNode);
244
+ }
245
+ updateFromJSON(serializedNode) {
246
+ return super.updateFromJSON(serializedNode).setLanguage(serializedNode.language).setTheme(serializedNode.theme);
189
247
  }
190
248
  exportJSON() {
191
249
  return {
192
250
  ...super.exportJSON(),
193
251
  language: this.getLanguage(),
194
- type: 'code',
195
- version: 1
252
+ theme: this.getTheme()
196
253
  };
197
254
  }
198
255
 
@@ -218,7 +275,7 @@ class CodeNode extends lexical.ElementNode {
218
275
  const firstPoint = anchor.isBefore(focus) ? anchor : focus;
219
276
  const firstSelectionNode = firstPoint.getNode();
220
277
  if (lexical.$isTextNode(firstSelectionNode)) {
221
- let node = getFirstCodeNodeOfLine(firstSelectionNode);
278
+ let node = $getFirstCodeNodeOfLine(firstSelectionNode);
222
279
  const insertNodes = [];
223
280
  // eslint-disable-next-line no-constant-condition
224
281
  while (true) {
@@ -279,18 +336,31 @@ class CodeNode extends lexical.ElementNode {
279
336
  }
280
337
  setLanguage(language) {
281
338
  const writable = this.getWritable();
282
- writable.__language = language;
283
- writable.__isSyntaxHighlightSupported = isLanguageSupportedByPrism(language);
339
+ writable.__language = language || undefined;
340
+ return writable;
284
341
  }
285
342
  getLanguage() {
286
343
  return this.getLatest().__language;
287
344
  }
345
+ setIsSyntaxHighlightSupported(isSupported) {
346
+ const writable = this.getWritable();
347
+ writable.__isSyntaxHighlightSupported = isSupported;
348
+ return writable;
349
+ }
288
350
  getIsSyntaxHighlightSupported() {
289
351
  return this.getLatest().__isSyntaxHighlightSupported;
290
352
  }
353
+ setTheme(theme) {
354
+ const writable = this.getWritable();
355
+ writable.__theme = theme || undefined;
356
+ return writable;
357
+ }
358
+ getTheme() {
359
+ return this.getLatest().__theme;
360
+ }
291
361
  }
292
- function $createCodeNode(language) {
293
- return lexical.$applyNodeReplacement(new CodeNode(language));
362
+ function $createCodeNode(language, theme) {
363
+ return lexical.$create(CodeNode).setLanguage(language).setTheme(theme);
294
364
  }
295
365
  function $isCodeNode(node) {
296
366
  return node instanceof CodeNode;
@@ -352,54 +422,11 @@ function isGitHubCodeTable(table) {
352
422
  *
353
423
  */
354
424
 
355
- const DEFAULT_CODE_LANGUAGE = 'javascript';
356
- const CODE_LANGUAGE_FRIENDLY_NAME_MAP = {
357
- c: 'C',
358
- clike: 'C-like',
359
- cpp: 'C++',
360
- css: 'CSS',
361
- html: 'HTML',
362
- java: 'Java',
363
- js: 'JavaScript',
364
- markdown: 'Markdown',
365
- objc: 'Objective-C',
366
- plain: 'Plain Text',
367
- powershell: 'PowerShell',
368
- py: 'Python',
369
- rust: 'Rust',
370
- sql: 'SQL',
371
- swift: 'Swift',
372
- typescript: 'TypeScript',
373
- xml: 'XML'
374
- };
375
- const CODE_LANGUAGE_MAP = {
376
- cpp: 'cpp',
377
- java: 'java',
378
- javascript: 'js',
379
- md: 'markdown',
380
- plaintext: 'plain',
381
- python: 'py',
382
- text: 'plain',
383
- ts: 'typescript'
384
- };
385
- function normalizeCodeLang(lang) {
386
- return CODE_LANGUAGE_MAP[lang] || lang;
387
- }
388
- function getLanguageFriendlyName(lang) {
389
- const _lang = normalizeCodeLang(lang);
390
- return CODE_LANGUAGE_FRIENDLY_NAME_MAP[_lang] || _lang;
391
- }
392
- const getDefaultCodeLanguage = () => DEFAULT_CODE_LANGUAGE;
393
- const getCodeLanguages = () => Object.keys(window.Prism.languages).filter(
394
- // Prism has several language helpers mixed into languages object
395
- // so filtering them out here to get langs list
396
- language => typeof window.Prism.languages[language] !== 'function').sort();
397
-
398
425
  /** @noInheritDoc */
399
426
  class CodeHighlightNode extends lexical.TextNode {
400
427
  /** @internal */
401
428
 
402
- constructor(text, highlightType, key) {
429
+ constructor(text = '', highlightType, key) {
403
430
  super(text, key);
404
431
  this.__highlightType = highlightType;
405
432
  }
@@ -413,6 +440,11 @@ class CodeHighlightNode extends lexical.TextNode {
413
440
  const self = this.getLatest();
414
441
  return self.__highlightType;
415
442
  }
443
+ setHighlightType(highlightType) {
444
+ const self = this.getWritable();
445
+ self.__highlightType = highlightType || undefined;
446
+ return self;
447
+ }
416
448
  canHaveFormat() {
417
449
  return false;
418
450
  }
@@ -437,19 +469,15 @@ class CodeHighlightNode extends lexical.TextNode {
437
469
  return update;
438
470
  }
439
471
  static importJSON(serializedNode) {
440
- const node = $createCodeHighlightNode(serializedNode.text, serializedNode.highlightType);
441
- node.setFormat(serializedNode.format);
442
- node.setDetail(serializedNode.detail);
443
- node.setMode(serializedNode.mode);
444
- node.setStyle(serializedNode.style);
445
- return node;
472
+ return $createCodeHighlightNode().updateFromJSON(serializedNode);
473
+ }
474
+ updateFromJSON(serializedNode) {
475
+ return super.updateFromJSON(serializedNode).setHighlightType(serializedNode.highlightType);
446
476
  }
447
477
  exportJSON() {
448
478
  return {
449
479
  ...super.exportJSON(),
450
- highlightType: this.getHighlightType(),
451
- type: 'code-highlight',
452
- version: 1
480
+ highlightType: this.getHighlightType()
453
481
  };
454
482
  }
455
483
 
@@ -467,46 +495,27 @@ class CodeHighlightNode extends lexical.TextNode {
467
495
  function getHighlightThemeClass(theme, highlightType) {
468
496
  return highlightType && theme && theme.codeHighlight && theme.codeHighlight[highlightType];
469
497
  }
470
- function $createCodeHighlightNode(text, highlightType) {
498
+ function $createCodeHighlightNode(text = '', highlightType) {
471
499
  return lexical.$applyNodeReplacement(new CodeHighlightNode(text, highlightType));
472
500
  }
473
501
  function $isCodeHighlightNode(node) {
474
502
  return node instanceof CodeHighlightNode;
475
503
  }
476
- function getFirstCodeNodeOfLine(anchor) {
477
- let previousNode = anchor;
478
- let node = anchor;
479
- while ($isCodeHighlightNode(node) || lexical.$isTabNode(node)) {
480
- previousNode = node;
481
- node = node.getPreviousSibling();
504
+
505
+ function $getLastMatchingCodeNode(anchor, direction) {
506
+ let matchingNode = anchor;
507
+ for (let caret = lexical.$getSiblingCaret(anchor, direction); caret && ($isCodeHighlightNode(caret.origin) || lexical.$isTabNode(caret.origin)); caret = LexicalUtils.$getAdjacentCaret(caret)) {
508
+ matchingNode = caret.origin;
482
509
  }
483
- return previousNode;
510
+ return matchingNode;
484
511
  }
485
- function getLastCodeNodeOfLine(anchor) {
486
- let nextNode = anchor;
487
- let node = anchor;
488
- while ($isCodeHighlightNode(node) || lexical.$isTabNode(node)) {
489
- nextNode = node;
490
- node = node.getNextSibling();
491
- }
492
- return nextNode;
512
+ function $getFirstCodeNodeOfLine(anchor) {
513
+ return $getLastMatchingCodeNode(anchor, 'previous');
493
514
  }
494
-
495
- /**
496
- * Copyright (c) Meta Platforms, Inc. and affiliates.
497
- *
498
- * This source code is licensed under the MIT license found in the
499
- * LICENSE file in the root directory of this source tree.
500
- *
501
- */
502
-
503
- const PrismTokenizer = {
504
- defaultLanguage: DEFAULT_CODE_LANGUAGE,
505
- tokenize(code, language) {
506
- return window.Prism.tokenize(code, window.Prism.languages[language || ''] || window.Prism.languages[this.defaultLanguage]);
507
- }
508
- };
509
- function getStartOfCodeInLine(anchor, offset) {
515
+ function $getLastCodeNodeOfLine(anchor) {
516
+ return $getLastMatchingCodeNode(anchor, 'next');
517
+ }
518
+ function $getStartOfCodeInLine(anchor, offset) {
510
519
  let last = null;
511
520
  let lastNonBlank = null;
512
521
  let node = anchor;
@@ -520,7 +529,7 @@ function getStartOfCodeInLine(anchor, offset) {
520
529
  break;
521
530
  }
522
531
  if (!($isCodeHighlightNode(node) || lexical.$isTabNode(node) || lexical.$isLineBreakNode(node))) {
523
- throw Error(`Expected a valid Code Node: CodeHighlightNode, TabNode, LineBreakNode`);
532
+ formatDevErrorMessage(`Expected a valid Code Node: CodeHighlightNode, TabNode, LineBreakNode`);
524
533
  }
525
534
  if (lexical.$isLineBreakNode(node)) {
526
535
  last = {
@@ -599,13 +608,297 @@ function findNextNonBlankInLine(anchor, offset) {
599
608
  }
600
609
  }
601
610
  }
602
- function getEndOfCodeInLine(anchor) {
603
- const lastNode = getLastCodeNodeOfLine(anchor);
611
+ function $getEndOfCodeInLine(anchor) {
612
+ const lastNode = $getLastCodeNodeOfLine(anchor);
604
613
  if (!!lexical.$isLineBreakNode(lastNode)) {
605
- throw Error(`Unexpected lineBreakNode in getEndOfCodeInLine`);
614
+ formatDevErrorMessage(`Unexpected lineBreakNode in getEndOfCodeInLine`);
606
615
  }
607
616
  return lastNode;
608
617
  }
618
+
619
+ (function (Prism) {
620
+
621
+ Prism.languages.diff = {
622
+ 'coord': [
623
+ // Match all kinds of coord lines (prefixed by "+++", "---" or "***").
624
+ /^(?:\*{3}|-{3}|\+{3}).*$/m,
625
+ // Match "@@ ... @@" coord lines in unified diff.
626
+ /^@@.*@@$/m,
627
+ // Match coord lines in normal diff (starts with a number).
628
+ /^\d.*$/m
629
+ ]
630
+
631
+ // deleted, inserted, unchanged, diff
632
+ };
633
+
634
+ /**
635
+ * A map from the name of a block to its line prefix.
636
+ *
637
+ * @type {Object<string, string>}
638
+ */
639
+ var PREFIXES = {
640
+ 'deleted-sign': '-',
641
+ 'deleted-arrow': '<',
642
+ 'inserted-sign': '+',
643
+ 'inserted-arrow': '>',
644
+ 'unchanged': ' ',
645
+ 'diff': '!',
646
+ };
647
+
648
+ // add a token for each prefix
649
+ Object.keys(PREFIXES).forEach(function (name) {
650
+ var prefix = PREFIXES[name];
651
+
652
+ var alias = [];
653
+ if (!/^\w+$/.test(name)) { // "deleted-sign" -> "deleted"
654
+ alias.push(/\w+/.exec(name)[0]);
655
+ }
656
+ if (name === 'diff') {
657
+ alias.push('bold');
658
+ }
659
+
660
+ Prism.languages.diff[name] = {
661
+ pattern: RegExp('^(?:[' + prefix + '].*(?:\r\n?|\n|(?![\\s\\S])))+', 'm'),
662
+ alias: alias,
663
+ inside: {
664
+ 'line': {
665
+ pattern: /(.)(?=[\s\S]).*(?:\r\n?|\n)?/,
666
+ lookbehind: true
667
+ },
668
+ 'prefix': {
669
+ pattern: /[\s\S]/,
670
+ alias: /\w+/.exec(name)[0]
671
+ }
672
+ }
673
+ };
674
+
675
+ });
676
+
677
+ // make prefixes available to Diff plugin
678
+ Object.defineProperty(Prism.languages.diff, 'PREFIXES', {
679
+ value: PREFIXES
680
+ });
681
+
682
+ }(Prism));
683
+
684
+ /**
685
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
686
+ *
687
+ * This source code is licensed under the MIT license found in the
688
+ * LICENSE file in the root directory of this source tree.
689
+ *
690
+ */
691
+
692
+ const Prism$1 = globalThis.Prism || window.Prism;
693
+ const CODE_LANGUAGE_FRIENDLY_NAME_MAP = {
694
+ c: 'C',
695
+ clike: 'C-like',
696
+ cpp: 'C++',
697
+ css: 'CSS',
698
+ html: 'HTML',
699
+ java: 'Java',
700
+ js: 'JavaScript',
701
+ markdown: 'Markdown',
702
+ objc: 'Objective-C',
703
+ plain: 'Plain Text',
704
+ powershell: 'PowerShell',
705
+ py: 'Python',
706
+ rust: 'Rust',
707
+ sql: 'SQL',
708
+ swift: 'Swift',
709
+ typescript: 'TypeScript',
710
+ xml: 'XML'
711
+ };
712
+ const CODE_LANGUAGE_MAP = {
713
+ cpp: 'cpp',
714
+ java: 'java',
715
+ javascript: 'js',
716
+ md: 'markdown',
717
+ plaintext: 'plain',
718
+ python: 'py',
719
+ text: 'plain',
720
+ ts: 'typescript'
721
+ };
722
+ function normalizeCodeLang(lang) {
723
+ return CODE_LANGUAGE_MAP[lang] || lang;
724
+ }
725
+ function getLanguageFriendlyName(lang) {
726
+ const _lang = normalizeCodeLang(lang);
727
+ return CODE_LANGUAGE_FRIENDLY_NAME_MAP[_lang] || _lang;
728
+ }
729
+ const getCodeLanguages = () => Object.keys(Prism$1.languages).filter(
730
+ // Prism has several language helpers mixed into languages object
731
+ // so filtering them out here to get langs list
732
+ language => typeof Prism$1.languages[language] !== 'function').sort();
733
+ function getCodeLanguageOptions() {
734
+ const options = [];
735
+ for (const [lang, friendlyName] of Object.entries(CODE_LANGUAGE_FRIENDLY_NAME_MAP)) {
736
+ options.push([lang, friendlyName]);
737
+ }
738
+ return options;
739
+ }
740
+
741
+ // Prism has no theme support
742
+ function getCodeThemeOptions() {
743
+ const options = [];
744
+ return options;
745
+ }
746
+ function getDiffedLanguage(language) {
747
+ const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
748
+ const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(language);
749
+ return diffLanguageMatch ? diffLanguageMatch[1] : null;
750
+ }
751
+ function isCodeLanguageLoaded(language) {
752
+ const diffedLanguage = getDiffedLanguage(language);
753
+ const langId = diffedLanguage ? diffedLanguage : language;
754
+ try {
755
+ // eslint-disable-next-line no-prototype-builtins
756
+ return langId ? Prism$1.languages.hasOwnProperty(langId) : false;
757
+ } catch (_unused) {
758
+ return false;
759
+ }
760
+ }
761
+ async function loadCodeLanguage(language, editor, codeNodeKey) {
762
+ // NOT IMPLEMENTED
763
+ }
764
+ function getTextContent(token) {
765
+ if (typeof token === 'string') {
766
+ return token;
767
+ } else if (Array.isArray(token)) {
768
+ return token.map(getTextContent).join('');
769
+ } else {
770
+ return getTextContent(token.content);
771
+ }
772
+ }
773
+
774
+ // The following code is extracted/adapted from prismjs v2
775
+ // It will probably be possible to use it directly from prism v2
776
+ // in the future when prismjs v2 is published and Lexical upgrades
777
+ // the prismsjs dependency
778
+ function tokenizeDiffHighlight(tokens, language) {
779
+ const diffLanguage = language;
780
+ const diffGrammar = Prism$1.languages[diffLanguage];
781
+ const env = {
782
+ tokens
783
+ };
784
+ const PREFIXES = Prism$1.languages.diff.PREFIXES;
785
+ for (const token of env.tokens) {
786
+ if (typeof token === 'string' || !(token.type in PREFIXES) || !Array.isArray(token.content)) {
787
+ continue;
788
+ }
789
+ const type = token.type;
790
+ let insertedPrefixes = 0;
791
+ const getPrefixToken = () => {
792
+ insertedPrefixes++;
793
+ return new Prism$1.Token('prefix', PREFIXES[type], type.replace(/^(\w+).*/, '$1'));
794
+ };
795
+ const withoutPrefixes = token.content.filter(t => typeof t === 'string' || t.type !== 'prefix');
796
+ const prefixCount = token.content.length - withoutPrefixes.length;
797
+ const diffTokens = Prism$1.tokenize(getTextContent(withoutPrefixes), diffGrammar);
798
+
799
+ // re-insert prefixes
800
+ // always add a prefix at the start
801
+ diffTokens.unshift(getPrefixToken());
802
+ const LINE_BREAK = /\r\n|\n/g;
803
+ const insertAfterLineBreakString = text => {
804
+ const result = [];
805
+ LINE_BREAK.lastIndex = 0;
806
+ let last = 0;
807
+ let m;
808
+ while (insertedPrefixes < prefixCount && (m = LINE_BREAK.exec(text))) {
809
+ const end = m.index + m[0].length;
810
+ result.push(text.slice(last, end));
811
+ last = end;
812
+ result.push(getPrefixToken());
813
+ }
814
+ if (result.length === 0) {
815
+ return undefined;
816
+ }
817
+ if (last < text.length) {
818
+ result.push(text.slice(last));
819
+ }
820
+ return result;
821
+ };
822
+ const insertAfterLineBreak = toks => {
823
+ for (let i = 0; i < toks.length && insertedPrefixes < prefixCount; i++) {
824
+ const tok = toks[i];
825
+ if (typeof tok === 'string') {
826
+ const inserted = insertAfterLineBreakString(tok);
827
+ if (inserted) {
828
+ toks.splice(i, 1, ...inserted);
829
+ i += inserted.length - 1;
830
+ }
831
+ } else if (typeof tok.content === 'string') {
832
+ const inserted = insertAfterLineBreakString(tok.content);
833
+ if (inserted) {
834
+ tok.content = inserted;
835
+ }
836
+ } else if (Array.isArray(tok.content)) {
837
+ insertAfterLineBreak(tok.content);
838
+ } else {
839
+ insertAfterLineBreak([tok.content]);
840
+ }
841
+ }
842
+ };
843
+ insertAfterLineBreak(diffTokens);
844
+ if (insertedPrefixes < prefixCount) {
845
+ // we are missing the last prefix
846
+ diffTokens.push(getPrefixToken());
847
+ }
848
+ token.content = diffTokens;
849
+ }
850
+ return env.tokens;
851
+ }
852
+ function $getHighlightNodes(codeNode, language) {
853
+ const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
854
+ const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(language);
855
+ const code = codeNode.getTextContent();
856
+ let tokens = Prism$1.tokenize(code, Prism$1.languages[diffLanguageMatch ? 'diff' : language]);
857
+ if (diffLanguageMatch) {
858
+ tokens = tokenizeDiffHighlight(tokens, diffLanguageMatch[1]);
859
+ }
860
+ return $mapTokensToLexicalStructure(tokens);
861
+ }
862
+ function $mapTokensToLexicalStructure(tokens, type) {
863
+ const nodes = [];
864
+ for (const token of tokens) {
865
+ if (typeof token === 'string') {
866
+ const partials = token.split(/(\n|\t)/);
867
+ const partialsLength = partials.length;
868
+ for (let i = 0; i < partialsLength; i++) {
869
+ const part = partials[i];
870
+ if (part === '\n' || part === '\r\n') {
871
+ nodes.push(lexical.$createLineBreakNode());
872
+ } else if (part === '\t') {
873
+ nodes.push(lexical.$createTabNode());
874
+ } else if (part.length > 0) {
875
+ nodes.push($createCodeHighlightNode(part, type));
876
+ }
877
+ }
878
+ } else {
879
+ const {
880
+ content,
881
+ alias
882
+ } = token;
883
+ if (typeof content === 'string') {
884
+ nodes.push(...$mapTokensToLexicalStructure([content], token.type === 'prefix' && typeof alias === 'string' ? alias : token.type));
885
+ } else if (Array.isArray(content)) {
886
+ nodes.push(...$mapTokensToLexicalStructure(content, token.type === 'unchanged' ? undefined : token.type));
887
+ }
888
+ }
889
+ }
890
+ return nodes;
891
+ }
892
+
893
+ const PrismTokenizer = {
894
+ $tokenize(codeNode, language) {
895
+ return $getHighlightNodes(codeNode, language || this.defaultLanguage);
896
+ },
897
+ defaultLanguage: DEFAULT_CODE_LANGUAGE,
898
+ tokenize(code, language) {
899
+ return Prism$1.tokenize(code, Prism$1.languages[language || ''] || Prism$1.languages[this.defaultLanguage]);
900
+ }
901
+ };
609
902
  function $textNodeTransform(node, editor, tokenizer) {
610
903
  // Since CodeNode has flat children structure we only need to check
611
904
  // if node's parent is a code node and run highlighting if so
@@ -653,18 +946,30 @@ function updateCodeGutter(node, editor) {
653
946
  const nodesCurrentlyHighlighting = new Set();
654
947
  function codeNodeTransform(node, editor, tokenizer) {
655
948
  const nodeKey = node.getKey();
656
- if (nodesCurrentlyHighlighting.has(nodeKey)) {
657
- return;
658
- }
659
- nodesCurrentlyHighlighting.add(nodeKey);
660
949
 
661
950
  // When new code block inserted it might not have language selected
662
951
  if (node.getLanguage() === undefined) {
663
952
  node.setLanguage(tokenizer.defaultLanguage);
664
953
  }
954
+ const language = node.getLanguage() || tokenizer.defaultLanguage;
955
+ if (isCodeLanguageLoaded(language)) {
956
+ if (!node.getIsSyntaxHighlightSupported()) {
957
+ node.setIsSyntaxHighlightSupported(true);
958
+ }
959
+ } else {
960
+ if (node.getIsSyntaxHighlightSupported()) {
961
+ node.setIsSyntaxHighlightSupported(false);
962
+ }
963
+ loadCodeLanguage();
964
+ return;
965
+ }
966
+ if (nodesCurrentlyHighlighting.has(nodeKey)) {
967
+ return;
968
+ }
969
+ nodesCurrentlyHighlighting.add(nodeKey);
665
970
 
666
971
  // Using nested update call to pass `skipTransforms` since we don't want
667
- // each individual codehighlight node to be transformed again as it's already
972
+ // each individual CodeHighlightNode to be transformed again as it's already
668
973
  // in its final state
669
974
  editor.update(() => {
670
975
  $updateAndRetainSelection(nodeKey, () => {
@@ -672,9 +977,11 @@ function codeNodeTransform(node, editor, tokenizer) {
672
977
  if (!$isCodeNode(currentNode) || !currentNode.isAttached()) {
673
978
  return false;
674
979
  }
675
- const code = currentNode.getTextContent();
676
- const tokens = tokenizer.tokenize(code, currentNode.getLanguage() || tokenizer.defaultLanguage);
677
- const highlightNodes = $getHighlightNodes(tokens);
980
+ //const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
981
+ const currentLanguage = currentNode.getLanguage() || tokenizer.defaultLanguage;
982
+ //const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(currentLanguage);
983
+
984
+ const highlightNodes = tokenizer.$tokenize(currentNode, currentLanguage);
678
985
  const diffRange = getDiffRange(currentNode.getChildren(), highlightNodes);
679
986
  const {
680
987
  from,
@@ -694,35 +1001,6 @@ function codeNodeTransform(node, editor, tokenizer) {
694
1001
  skipTransforms: true
695
1002
  });
696
1003
  }
697
- function $getHighlightNodes(tokens, type) {
698
- const nodes = [];
699
- for (const token of tokens) {
700
- if (typeof token === 'string') {
701
- const partials = token.split(/(\n|\t)/);
702
- const partialsLength = partials.length;
703
- for (let i = 0; i < partialsLength; i++) {
704
- const part = partials[i];
705
- if (part === '\n' || part === '\r\n') {
706
- nodes.push(lexical.$createLineBreakNode());
707
- } else if (part === '\t') {
708
- nodes.push(lexical.$createTabNode());
709
- } else if (part.length > 0) {
710
- nodes.push($createCodeHighlightNode(part, type));
711
- }
712
- }
713
- } else {
714
- const {
715
- content
716
- } = token;
717
- if (typeof content === 'string') {
718
- nodes.push(...$getHighlightNodes([content], token.type));
719
- } else if (Array.isArray(content)) {
720
- nodes.push(...$getHighlightNodes(content, token.type));
721
- }
722
- }
723
- }
724
- return nodes;
725
- }
726
1004
 
727
1005
  // Wrapping update function into selection retainer, that tries to keep cursor at the same
728
1006
  // position as before.
@@ -809,43 +1087,66 @@ function getDiffRange(prevNodes, nextNodes) {
809
1087
  };
810
1088
  }
811
1089
  function isEqual(nodeA, nodeB) {
812
- // Only checking for code higlight nodes, tabs and linebreaks. If it's regular text node
1090
+ // Only checking for code highlight nodes, tabs and linebreaks. If it's regular text node
813
1091
  // returning false so that it's transformed into code highlight node
814
1092
  return $isCodeHighlightNode(nodeA) && $isCodeHighlightNode(nodeB) && nodeA.__text === nodeB.__text && nodeA.__highlightType === nodeB.__highlightType || lexical.$isTabNode(nodeA) && lexical.$isTabNode(nodeB) || lexical.$isLineBreakNode(nodeA) && lexical.$isLineBreakNode(nodeB);
815
1093
  }
1094
+
1095
+ /**
1096
+ * Returns a boolean.
1097
+ * Check that the selection span is within a single CodeNode.
1098
+ * This is used to guard against executing handlers that can only be
1099
+ * applied in a single CodeNode context
1100
+ */
816
1101
  function $isSelectionInCode(selection) {
817
1102
  if (!lexical.$isRangeSelection(selection)) {
818
1103
  return false;
819
1104
  }
820
1105
  const anchorNode = selection.anchor.getNode();
1106
+ const maybeAnchorCodeNode = $isCodeNode(anchorNode) ? anchorNode : anchorNode.getParent();
821
1107
  const focusNode = selection.focus.getNode();
822
- if (anchorNode.is(focusNode) && $isCodeNode(anchorNode)) {
823
- return true;
824
- }
825
- const anchorParent = anchorNode.getParent();
826
- return $isCodeNode(anchorParent) && anchorParent.is(focusNode.getParent());
1108
+ const maybeFocusCodeNode = $isCodeNode(focusNode) ? focusNode : focusNode.getParent();
1109
+ return $isCodeNode(maybeAnchorCodeNode) && maybeAnchorCodeNode.is(maybeFocusCodeNode);
827
1110
  }
1111
+
1112
+ /**
1113
+ * Returns an Array of code lines
1114
+ * Take the sequence of LineBreakNode | TabNode | CodeHighlightNode forming
1115
+ * the selection and split it by LineBreakNode.
1116
+ * If the selection ends at the start of the last line, it is considered empty.
1117
+ * Empty lines are discarded.
1118
+ */
828
1119
  function $getCodeLines(selection) {
829
1120
  const nodes = selection.getNodes();
830
- const lines = [[]];
1121
+ const lines = [];
831
1122
  if (nodes.length === 1 && $isCodeNode(nodes[0])) {
832
1123
  return lines;
833
1124
  }
834
- let lastLine = lines[0];
1125
+ let lastLine = [];
835
1126
  for (let i = 0; i < nodes.length; i++) {
836
1127
  const node = nodes[i];
837
1128
  if (!($isCodeHighlightNode(node) || lexical.$isTabNode(node) || lexical.$isLineBreakNode(node))) {
838
- throw Error(`Expected selection to be inside CodeBlock and consisting of CodeHighlightNode, TabNode and LineBreakNode`);
1129
+ formatDevErrorMessage(`Expected selection to be inside CodeBlock and consisting of CodeHighlightNode, TabNode and LineBreakNode`);
839
1130
  }
840
1131
  if (lexical.$isLineBreakNode(node)) {
841
- if (i !== 0 && lastLine.length > 0) {
842
- lastLine = [];
1132
+ if (lastLine.length > 0) {
843
1133
  lines.push(lastLine);
1134
+ lastLine = [];
844
1135
  }
845
1136
  } else {
846
1137
  lastLine.push(node);
847
1138
  }
848
1139
  }
1140
+ if (lastLine.length > 0) {
1141
+ const selectionEnd = selection.isBackward() ? selection.anchor : selection.focus;
1142
+
1143
+ // Discard the last line if the selection ends exactly at the
1144
+ // start of the line (no real selection)
1145
+ const lastPoint = lexical.$createPoint(lastLine[0].getKey(), 0, 'text');
1146
+ if (!selectionEnd.is(lastPoint)) {
1147
+ lines.push(lastLine);
1148
+ }
1149
+ }
849
1150
  return lines;
850
1151
  }
851
1152
  function $handleTab(shiftKey) {
@@ -855,38 +1156,60 @@ function $handleTab(shiftKey) {
855
1156
  }
856
1157
  const indentOrOutdent = !shiftKey ? lexical.INDENT_CONTENT_COMMAND : lexical.OUTDENT_CONTENT_COMMAND;
857
1158
  const tabOrOutdent = !shiftKey ? lexical.INSERT_TAB_COMMAND : lexical.OUTDENT_CONTENT_COMMAND;
858
- // 1. If multiple lines selected: indent/outdent
859
- const codeLines = $getCodeLines(selection);
860
- if (codeLines.length > 1) {
861
- return indentOrOutdent;
862
- }
863
- // 2. If entire line selected: indent/outdent
864
- const selectionNodes = selection.getNodes();
865
- const firstNode = selectionNodes[0];
866
- if (!($isCodeNode(firstNode) || $isCodeHighlightNode(firstNode) || lexical.$isTabNode(firstNode) || lexical.$isLineBreakNode(firstNode))) {
867
- throw Error(`Expected selection firstNode to be CodeHighlightNode or TabNode`);
1159
+ const anchor = selection.anchor;
1160
+ const focus = selection.focus;
1161
+
1162
+ // 1. early decision when there is no real selection
1163
+ if (anchor.is(focus)) {
1164
+ return tabOrOutdent;
868
1165
  }
869
- if ($isCodeNode(firstNode)) {
1166
+
1167
+ // 2. If only empty lines or multiple non-empty lines are selected: indent/outdent
1168
+ const codeLines = $getCodeLines(selection);
1169
+ if (codeLines.length !== 1) {
870
1170
  return indentOrOutdent;
871
1171
  }
872
- const firstOfLine = getFirstCodeNodeOfLine(firstNode);
873
- const lastOfLine = getLastCodeNodeOfLine(firstNode);
874
- const anchor = selection.anchor;
875
- const focus = selection.focus;
1172
+ const codeLine = codeLines[0];
1173
+ const codeLineLength = codeLine.length;
1174
+ if (!(codeLineLength !== 0)) {
1175
+ formatDevErrorMessage(`$getCodeLines only extracts non-empty lines`);
1176
+ } // Take into account the direction of the selection
876
1177
  let selectionFirst;
877
1178
  let selectionLast;
878
- if (focus.isBefore(anchor)) {
1179
+ if (selection.isBackward()) {
879
1180
  selectionFirst = focus;
880
1181
  selectionLast = anchor;
881
1182
  } else {
882
1183
  selectionFirst = anchor;
883
1184
  selectionLast = focus;
884
1185
  }
885
- if (firstOfLine !== null && lastOfLine !== null && selectionFirst.key === firstOfLine.getKey() && selectionFirst.offset === 0 && selectionLast.key === lastOfLine.getKey() && selectionLast.offset === lastOfLine.getTextContentSize()) {
1186
+
1187
+ // find boundary elements of the line
1188
+ // since codeLine only contains TabNode | CodeHighlightNode
1189
+ // the result of these functions should is of Type TabNode | CodeHighlightNode
1190
+ const firstOfLine = $getFirstCodeNodeOfLine(codeLine[0]);
1191
+ const lastOfLine = $getLastCodeNodeOfLine(codeLine[0]);
1192
+ const anchorOfLine = lexical.$createPoint(firstOfLine.getKey(), 0, 'text');
1193
+ const focusOfLine = lexical.$createPoint(lastOfLine.getKey(), lastOfLine.getTextContentSize(), 'text');
1194
+
1195
+ // 3. multiline because selection started strictly before the line
1196
+ if (selectionFirst.isBefore(anchorOfLine)) {
886
1197
  return indentOrOutdent;
887
1198
  }
888
- // 3. Else: tab/outdent
889
- return tabOrOutdent;
1199
+
1200
+ // 4. multiline because the selection stops strictly after the line
1201
+ if (focusOfLine.isBefore(selectionLast)) {
1202
+ return indentOrOutdent;
1203
+ }
1204
+
1205
+ // The selection if within the line.
1206
+ // 4. If it does not touch both borders, it needs a tab
1207
+ if (anchorOfLine.isBefore(selectionFirst) || selectionLast.isBefore(focusOfLine)) {
1208
+ return tabOrOutdent;
1209
+ }
1210
+
1211
+ // 5. Selection is matching a full line on non-empty code
1212
+ return indentOrOutdent;
890
1213
  }
891
1214
  function $handleMultilineIndent(type) {
892
1215
  const selection = lexical.$getSelection();
@@ -895,52 +1218,55 @@ function $handleMultilineIndent(type) {
895
1218
  }
896
1219
  const codeLines = $getCodeLines(selection);
897
1220
  const codeLinesLength = codeLines.length;
898
- // Multiple lines selection
899
- if (codeLines.length > 1) {
900
- for (let i = 0; i < codeLinesLength; i++) {
901
- const line = codeLines[i];
902
- if (line.length > 0) {
903
- let firstOfLine = line[0];
904
- // First and last lines might not be complete
905
- if (i === 0) {
906
- firstOfLine = getFirstCodeNodeOfLine(firstOfLine);
907
- }
908
- if (firstOfLine !== null) {
909
- if (type === lexical.INDENT_CONTENT_COMMAND) {
910
- firstOfLine.insertBefore(lexical.$createTabNode());
911
- } else if (lexical.$isTabNode(firstOfLine)) {
912
- firstOfLine.remove();
913
- }
914
- }
915
- }
916
- }
917
- return true;
918
- }
919
- // Just one line
920
- const selectionNodes = selection.getNodes();
921
- const firstNode = selectionNodes[0];
922
- if (!($isCodeNode(firstNode) || $isCodeHighlightNode(firstNode) || lexical.$isTabNode(firstNode) || lexical.$isLineBreakNode(firstNode))) {
923
- throw Error(`Expected selection firstNode to be CodeHighlightNode or CodeTabNode`);
924
- }
925
- if ($isCodeNode(firstNode)) {
926
- // CodeNode is empty
1221
+
1222
+ // Special Indent case
1223
+ // Selection is collapsed at the beginning of a line
1224
+ if (codeLinesLength === 0 && selection.isCollapsed()) {
927
1225
  if (type === lexical.INDENT_CONTENT_COMMAND) {
928
1226
  selection.insertNodes([lexical.$createTabNode()]);
929
1227
  }
930
1228
  return true;
931
1229
  }
932
- const firstOfLine = getFirstCodeNodeOfLine(firstNode);
933
- if (!(firstOfLine !== null)) {
934
- throw Error(`Expected getFirstCodeNodeOfLine to return a valid Code Node`);
1230
+
1231
+ // Special Indent case
1232
+ // Selection is matching only one LineBreak
1233
+ if (codeLinesLength === 0 && type === lexical.INDENT_CONTENT_COMMAND && selection.getTextContent() === '\n') {
1234
+ const tabNode = lexical.$createTabNode();
1235
+ const lineBreakNode = lexical.$createLineBreakNode();
1236
+ const direction = selection.isBackward() ? 'previous' : 'next';
1237
+ selection.insertNodes([tabNode, lineBreakNode]);
1238
+ lexical.$setSelectionFromCaretRange(lexical.$getCaretRangeInDirection(lexical.$getCaretRange(lexical.$getTextPointCaret(tabNode, 'next', 0), lexical.$normalizeCaret(lexical.$getSiblingCaret(lineBreakNode, 'next'))), direction));
1239
+ return true;
935
1240
  }
936
- if (type === lexical.INDENT_CONTENT_COMMAND) {
937
- if (lexical.$isLineBreakNode(firstOfLine)) {
938
- firstOfLine.insertAfter(lexical.$createTabNode());
939
- } else {
940
- firstOfLine.insertBefore(lexical.$createTabNode());
1241
+
1242
+ // Indent Non Empty Lines
1243
+ for (let i = 0; i < codeLinesLength; i++) {
1244
+ const line = codeLines[i];
1245
+ // a line here is never empty
1246
+ if (line.length > 0) {
1247
+ let firstOfLine = line[0];
1248
+
1249
+ // make sure to consider the first node on the first line
1250
+ // because the line might not be fully selected
1251
+ if (i === 0) {
1252
+ firstOfLine = $getFirstCodeNodeOfLine(firstOfLine);
1253
+ }
1254
+ if (type === lexical.INDENT_CONTENT_COMMAND) {
1255
+ const tabNode = lexical.$createTabNode();
1256
+ firstOfLine.insertBefore(tabNode);
1257
+ // First real code line may need selection adjustment
1258
+ // when firstOfLine is at the selection boundary
1259
+ if (i === 0) {
1260
+ const anchorKey = selection.isBackward() ? 'focus' : 'anchor';
1261
+ const anchorLine = lexical.$createPoint(firstOfLine.getKey(), 0, 'text');
1262
+ if (selection[anchorKey].is(anchorLine)) {
1263
+ selection[anchorKey].set(tabNode.getKey(), 0, 'text');
1264
+ }
1265
+ }
1266
+ } else if (lexical.$isTabNode(firstOfLine)) {
1267
+ firstOfLine.remove();
1268
+ }
941
1269
  }
942
- } else if (lexical.$isTabNode(firstOfLine)) {
943
- firstOfLine.remove();
944
1270
  }
945
1271
  return true;
946
1272
  }
@@ -969,7 +1295,7 @@ function $handleShiftLines(type, event) {
969
1295
  }
970
1296
  if (!event.altKey) {
971
1297
  // Handle moving selection out of the code block, given there are no
972
- // sibling thats can natively take the selection.
1298
+ // siblings that can natively take the selection.
973
1299
  if (selection.isCollapsed()) {
974
1300
  const codeNode = anchorNode.getParentOrThrow();
975
1301
  if (arrowIsUp && anchorOffset === 0 && anchorNode.getPreviousSibling() === null) {
@@ -993,11 +1319,11 @@ function $handleShiftLines(type, event) {
993
1319
  let start;
994
1320
  let end;
995
1321
  if (anchorNode.isBefore(focusNode)) {
996
- start = getFirstCodeNodeOfLine(anchorNode);
997
- end = getLastCodeNodeOfLine(focusNode);
1322
+ start = $getFirstCodeNodeOfLine(anchorNode);
1323
+ end = $getLastCodeNodeOfLine(focusNode);
998
1324
  } else {
999
- start = getFirstCodeNodeOfLine(focusNode);
1000
- end = getLastCodeNodeOfLine(anchorNode);
1325
+ start = $getFirstCodeNodeOfLine(focusNode);
1326
+ end = $getLastCodeNodeOfLine(anchorNode);
1001
1327
  }
1002
1328
  if (start == null || end == null) {
1003
1329
  return false;
@@ -1024,7 +1350,7 @@ function $handleShiftLines(type, event) {
1024
1350
  if (sibling == null) {
1025
1351
  return true;
1026
1352
  }
1027
- const maybeInsertionPoint = $isCodeHighlightNode(sibling) || lexical.$isTabNode(sibling) || lexical.$isLineBreakNode(sibling) ? arrowIsUp ? getFirstCodeNodeOfLine(sibling) : getLastCodeNodeOfLine(sibling) : null;
1353
+ const maybeInsertionPoint = $isCodeHighlightNode(sibling) || lexical.$isTabNode(sibling) || lexical.$isLineBreakNode(sibling) ? arrowIsUp ? $getFirstCodeNodeOfLine(sibling) : $getLastCodeNodeOfLine(sibling) : null;
1028
1354
  let insertionPoint = maybeInsertionPoint != null ? maybeInsertionPoint : sibling;
1029
1355
  linebreak.remove();
1030
1356
  range.forEach(node => node.remove());
@@ -1054,11 +1380,13 @@ function $handleMoveTo(type, event) {
1054
1380
  const anchorNode = anchor.getNode();
1055
1381
  const focusNode = focus.getNode();
1056
1382
  const isMoveToStart = type === lexical.MOVE_TO_START;
1057
- if (!($isCodeHighlightNode(anchorNode) || lexical.$isTabNode(anchorNode)) || !($isCodeHighlightNode(focusNode) || lexical.$isTabNode(focusNode))) {
1383
+
1384
+ // Ensure the selection is within the codeblock
1385
+ if (!$isSelectionInCode(selection) || !($isCodeHighlightNode(anchorNode) || lexical.$isTabNode(anchorNode)) || !($isCodeHighlightNode(focusNode) || lexical.$isTabNode(focusNode))) {
1058
1386
  return false;
1059
1387
  }
1060
1388
  if (isMoveToStart) {
1061
- const start = getStartOfCodeInLine(focusNode, focus.offset);
1389
+ const start = $getStartOfCodeInLine(focusNode, focus.offset);
1062
1390
  if (start !== null) {
1063
1391
  const {
1064
1392
  node,
@@ -1073,7 +1401,7 @@ function $handleMoveTo(type, event) {
1073
1401
  focusNode.getParentOrThrow().selectStart();
1074
1402
  }
1075
1403
  } else {
1076
- const node = getEndOfCodeInLine(focusNode);
1404
+ const node = $getEndOfCodeInLine(focusNode);
1077
1405
  node.select();
1078
1406
  }
1079
1407
  event.preventDefault();
@@ -1087,20 +1415,28 @@ function registerCodeHighlighting(editor, tokenizer) {
1087
1415
  if (tokenizer == null) {
1088
1416
  tokenizer = PrismTokenizer;
1089
1417
  }
1090
- return LexicalUtils.mergeRegister(editor.registerMutationListener(CodeNode, mutations => {
1091
- editor.update(() => {
1092
- for (const [key, type] of mutations) {
1093
- if (type !== 'destroyed') {
1094
- const node = lexical.$getNodeByKey(key);
1095
- if (node !== null) {
1096
- updateCodeGutter(node, editor);
1418
+ const registrations = [];
1419
+
1420
+ // Only register the mutation listener if not in headless mode
1421
+ if (editor._headless !== true) {
1422
+ registrations.push(editor.registerMutationListener(CodeNode, mutations => {
1423
+ editor.update(() => {
1424
+ for (const [key, type] of mutations) {
1425
+ if (type !== 'destroyed') {
1426
+ const node = lexical.$getNodeByKey(key);
1427
+ if (node !== null) {
1428
+ updateCodeGutter(node, editor);
1429
+ }
1097
1430
  }
1098
1431
  }
1099
- }
1100
- });
1101
- }, {
1102
- skipInitialization: false
1103
- }), editor.registerNodeTransform(CodeNode, node => codeNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(lexical.TextNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(CodeHighlightNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerCommand(lexical.KEY_TAB_COMMAND, event => {
1432
+ });
1433
+ }, {
1434
+ skipInitialization: false
1435
+ }));
1436
+ }
1437
+
1438
+ // Add the rest of the registrations
1439
+ registrations.push(editor.registerNodeTransform(CodeNode, node => codeNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(lexical.TextNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(CodeHighlightNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerCommand(lexical.KEY_TAB_COMMAND, event => {
1104
1440
  const command = $handleTab(event.shiftKey);
1105
1441
  if (command === null) {
1106
1442
  return false;
@@ -1115,11 +1451,70 @@ function registerCodeHighlighting(editor, tokenizer) {
1115
1451
  }
1116
1452
  lexical.$insertNodes([lexical.$createTabNode()]);
1117
1453
  return true;
1118
- }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.INDENT_CONTENT_COMMAND, payload => $handleMultilineIndent(lexical.INDENT_CONTENT_COMMAND), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.OUTDENT_CONTENT_COMMAND, payload => $handleMultilineIndent(lexical.OUTDENT_CONTENT_COMMAND), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_ARROW_UP_COMMAND, payload => $handleShiftLines(lexical.KEY_ARROW_UP_COMMAND, payload), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_ARROW_DOWN_COMMAND, payload => $handleShiftLines(lexical.KEY_ARROW_DOWN_COMMAND, payload), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.MOVE_TO_END, payload => $handleMoveTo(lexical.MOVE_TO_END, payload), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.MOVE_TO_START, payload => $handleMoveTo(lexical.MOVE_TO_START, payload), lexical.COMMAND_PRIORITY_LOW));
1454
+ }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.INDENT_CONTENT_COMMAND, payload => $handleMultilineIndent(lexical.INDENT_CONTENT_COMMAND), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.OUTDENT_CONTENT_COMMAND, payload => $handleMultilineIndent(lexical.OUTDENT_CONTENT_COMMAND), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_ARROW_UP_COMMAND, event => {
1455
+ const selection = lexical.$getSelection();
1456
+ if (!lexical.$isRangeSelection(selection)) {
1457
+ return false;
1458
+ }
1459
+ const {
1460
+ anchor
1461
+ } = selection;
1462
+ const anchorNode = anchor.getNode();
1463
+ if (!$isSelectionInCode(selection)) {
1464
+ return false;
1465
+ }
1466
+ // If at the start of a code block, prevent selection from moving out
1467
+ if (selection.isCollapsed() && anchor.offset === 0 && anchorNode.getPreviousSibling() === null && $isCodeNode(anchorNode.getParentOrThrow())) {
1468
+ event.preventDefault();
1469
+ return true;
1470
+ }
1471
+ return $handleShiftLines(lexical.KEY_ARROW_UP_COMMAND, event);
1472
+ }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_ARROW_DOWN_COMMAND, event => {
1473
+ const selection = lexical.$getSelection();
1474
+ if (!lexical.$isRangeSelection(selection)) {
1475
+ return false;
1476
+ }
1477
+ const {
1478
+ anchor
1479
+ } = selection;
1480
+ const anchorNode = anchor.getNode();
1481
+ if (!$isSelectionInCode(selection)) {
1482
+ return false;
1483
+ }
1484
+ // If at the end of a code block, prevent selection from moving out
1485
+ if (selection.isCollapsed() && anchor.offset === anchorNode.getTextContentSize() && anchorNode.getNextSibling() === null && $isCodeNode(anchorNode.getParentOrThrow())) {
1486
+ event.preventDefault();
1487
+ return true;
1488
+ }
1489
+ return $handleShiftLines(lexical.KEY_ARROW_DOWN_COMMAND, event);
1490
+ }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.MOVE_TO_START, event => $handleMoveTo(lexical.MOVE_TO_START, event), lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.MOVE_TO_END, event => $handleMoveTo(lexical.MOVE_TO_END, event), lexical.COMMAND_PRIORITY_LOW));
1491
+ return LexicalUtils.mergeRegister(...registrations);
1119
1492
  }
1120
1493
 
1494
+ /**
1495
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1496
+ *
1497
+ * This source code is licensed under the MIT license found in the
1498
+ * LICENSE file in the root directory of this source tree.
1499
+ *
1500
+ */
1501
+
1502
+
1503
+ /** @deprecated renamed to {@link $getFirstCodeNodeOfLine} by @lexical/eslint-plugin rules-of-lexical */
1504
+ const getFirstCodeNodeOfLine = $getFirstCodeNodeOfLine;
1505
+ /** @deprecated renamed to {@link $getLastCodeNodeOfLine} by @lexical/eslint-plugin rules-of-lexical */
1506
+ const getLastCodeNodeOfLine = $getLastCodeNodeOfLine;
1507
+ /** @deprecated renamed to {@link $getEndOfCodeInLine} by @lexical/eslint-plugin rules-of-lexical */
1508
+ const getEndOfCodeInLine = $getEndOfCodeInLine;
1509
+ /** @deprecated renamed to {@link $getStartOfCodeInLine} by @lexical/eslint-plugin rules-of-lexical */
1510
+ const getStartOfCodeInLine = $getStartOfCodeInLine;
1511
+
1121
1512
  exports.$createCodeHighlightNode = $createCodeHighlightNode;
1122
1513
  exports.$createCodeNode = $createCodeNode;
1514
+ exports.$getEndOfCodeInLine = $getEndOfCodeInLine;
1515
+ exports.$getFirstCodeNodeOfLine = $getFirstCodeNodeOfLine;
1516
+ exports.$getLastCodeNodeOfLine = $getLastCodeNodeOfLine;
1517
+ exports.$getStartOfCodeInLine = $getStartOfCodeInLine;
1123
1518
  exports.$isCodeHighlightNode = $isCodeHighlightNode;
1124
1519
  exports.$isCodeNode = $isCodeNode;
1125
1520
  exports.CODE_LANGUAGE_FRIENDLY_NAME_MAP = CODE_LANGUAGE_FRIENDLY_NAME_MAP;
@@ -1128,7 +1523,9 @@ exports.CodeHighlightNode = CodeHighlightNode;
1128
1523
  exports.CodeNode = CodeNode;
1129
1524
  exports.DEFAULT_CODE_LANGUAGE = DEFAULT_CODE_LANGUAGE;
1130
1525
  exports.PrismTokenizer = PrismTokenizer;
1526
+ exports.getCodeLanguageOptions = getCodeLanguageOptions;
1131
1527
  exports.getCodeLanguages = getCodeLanguages;
1528
+ exports.getCodeThemeOptions = getCodeThemeOptions;
1132
1529
  exports.getDefaultCodeLanguage = getDefaultCodeLanguage;
1133
1530
  exports.getEndOfCodeInLine = getEndOfCodeInLine;
1134
1531
  exports.getFirstCodeNodeOfLine = getFirstCodeNodeOfLine;
@@ -1136,4 +1533,5 @@ exports.getLanguageFriendlyName = getLanguageFriendlyName;
1136
1533
  exports.getLastCodeNodeOfLine = getLastCodeNodeOfLine;
1137
1534
  exports.getStartOfCodeInLine = getStartOfCodeInLine;
1138
1535
  exports.normalizeCodeLang = normalizeCodeLang;
1536
+ exports.normalizeCodeLanguage = normalizeCodeLang;
1139
1537
  exports.registerCodeHighlighting = registerCodeHighlighting;