@lexical/code-prism 0.41.1-nightly.20260309.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.
@@ -0,0 +1,951 @@
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
+ 'use strict';
10
+
11
+ var codeCore = require('@lexical/code-core');
12
+ var lexical = require('lexical');
13
+ require('prismjs');
14
+ require('prismjs/components/prism-clike');
15
+ require('prismjs/components/prism-javascript');
16
+ require('prismjs/components/prism-markup');
17
+ require('prismjs/components/prism-markdown');
18
+ require('prismjs/components/prism-c');
19
+ require('prismjs/components/prism-css');
20
+ require('prismjs/components/prism-objectivec');
21
+ require('prismjs/components/prism-sql');
22
+ require('prismjs/components/prism-powershell');
23
+ require('prismjs/components/prism-python');
24
+ require('prismjs/components/prism-rust');
25
+ require('prismjs/components/prism-swift');
26
+ require('prismjs/components/prism-typescript');
27
+ require('prismjs/components/prism-java');
28
+ require('prismjs/components/prism-cpp');
29
+
30
+ /**
31
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
32
+ *
33
+ * This source code is licensed under the MIT license found in the
34
+ * LICENSE file in the root directory of this source tree.
35
+ *
36
+ */
37
+
38
+ // Do not require this module directly! Use normal `invariant` calls.
39
+
40
+ function formatDevErrorMessage(message) {
41
+ throw new Error(message);
42
+ }
43
+
44
+ /**
45
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
46
+ *
47
+ * This source code is licensed under the MIT license found in the
48
+ * LICENSE file in the root directory of this source tree.
49
+ *
50
+ */
51
+
52
+ // invariant(condition, message) will refine types based on "condition", and
53
+ // if "condition" is false will throw an error. This function is special-cased
54
+ // in flow itself, so we can't name it anything else.
55
+ function invariant(cond, message, ...args) {
56
+ if (cond) {
57
+ return;
58
+ }
59
+ throw new Error('Internal Lexical error: invariant() is meant to be replaced at compile ' + 'time. There is no runtime version. Error: ' + message);
60
+ }
61
+
62
+ (function (Prism) {
63
+
64
+ Prism.languages.diff = {
65
+ 'coord': [
66
+ // Match all kinds of coord lines (prefixed by "+++", "---" or "***").
67
+ /^(?:\*{3}|-{3}|\+{3}).*$/m,
68
+ // Match "@@ ... @@" coord lines in unified diff.
69
+ /^@@.*@@$/m,
70
+ // Match coord lines in normal diff (starts with a number).
71
+ /^\d.*$/m
72
+ ]
73
+
74
+ // deleted, inserted, unchanged, diff
75
+ };
76
+
77
+ /**
78
+ * A map from the name of a block to its line prefix.
79
+ *
80
+ * @type {Object<string, string>}
81
+ */
82
+ var PREFIXES = {
83
+ 'deleted-sign': '-',
84
+ 'deleted-arrow': '<',
85
+ 'inserted-sign': '+',
86
+ 'inserted-arrow': '>',
87
+ 'unchanged': ' ',
88
+ 'diff': '!',
89
+ };
90
+
91
+ // add a token for each prefix
92
+ Object.keys(PREFIXES).forEach(function (name) {
93
+ var prefix = PREFIXES[name];
94
+
95
+ var alias = [];
96
+ if (!/^\w+$/.test(name)) { // "deleted-sign" -> "deleted"
97
+ alias.push(/\w+/.exec(name)[0]);
98
+ }
99
+ if (name === 'diff') {
100
+ alias.push('bold');
101
+ }
102
+
103
+ Prism.languages.diff[name] = {
104
+ pattern: RegExp('^(?:[' + prefix + '].*(?:\r\n?|\n|(?![\\s\\S])))+', 'm'),
105
+ alias: alias,
106
+ inside: {
107
+ 'line': {
108
+ pattern: /(.)(?=[\s\S]).*(?:\r\n?|\n)?/,
109
+ lookbehind: true
110
+ },
111
+ 'prefix': {
112
+ pattern: /[\s\S]/,
113
+ alias: /\w+/.exec(name)[0]
114
+ }
115
+ }
116
+ };
117
+
118
+ });
119
+
120
+ // make prefixes available to Diff plugin
121
+ Object.defineProperty(Prism.languages.diff, 'PREFIXES', {
122
+ value: PREFIXES
123
+ });
124
+
125
+ }(Prism));
126
+
127
+ /**
128
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
129
+ *
130
+ * This source code is licensed under the MIT license found in the
131
+ * LICENSE file in the root directory of this source tree.
132
+ *
133
+ */
134
+
135
+ const Prism$1 = globalThis.Prism || window.Prism;
136
+ const CODE_LANGUAGE_FRIENDLY_NAME_MAP = {
137
+ c: 'C',
138
+ clike: 'C-like',
139
+ cpp: 'C++',
140
+ css: 'CSS',
141
+ html: 'HTML',
142
+ java: 'Java',
143
+ js: 'JavaScript',
144
+ markdown: 'Markdown',
145
+ objc: 'Objective-C',
146
+ plain: 'Plain Text',
147
+ powershell: 'PowerShell',
148
+ py: 'Python',
149
+ rust: 'Rust',
150
+ sql: 'SQL',
151
+ swift: 'Swift',
152
+ typescript: 'TypeScript',
153
+ xml: 'XML'
154
+ };
155
+ const CODE_LANGUAGE_MAP = {
156
+ cpp: 'cpp',
157
+ java: 'java',
158
+ javascript: 'js',
159
+ md: 'markdown',
160
+ plaintext: 'plain',
161
+ python: 'py',
162
+ text: 'plain',
163
+ ts: 'typescript'
164
+ };
165
+ function normalizeCodeLanguage(lang) {
166
+ return CODE_LANGUAGE_MAP[lang] || lang;
167
+ }
168
+ function getLanguageFriendlyName(lang) {
169
+ const _lang = normalizeCodeLanguage(lang);
170
+ return CODE_LANGUAGE_FRIENDLY_NAME_MAP[_lang] || _lang;
171
+ }
172
+ const getCodeLanguages = () => Object.keys(Prism$1.languages).filter(
173
+ // Prism has several language helpers mixed into languages object
174
+ // so filtering them out here to get langs list
175
+ language => typeof Prism$1.languages[language] !== 'function').sort();
176
+ function getCodeLanguageOptions() {
177
+ const options = [];
178
+ for (const [lang, friendlyName] of Object.entries(CODE_LANGUAGE_FRIENDLY_NAME_MAP)) {
179
+ options.push([lang, friendlyName]);
180
+ }
181
+ return options;
182
+ }
183
+
184
+ // Prism has no theme support
185
+ function getCodeThemeOptions() {
186
+ const options = [];
187
+ return options;
188
+ }
189
+ function getDiffedLanguage(language) {
190
+ const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
191
+ const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(language);
192
+ return diffLanguageMatch ? diffLanguageMatch[1] : null;
193
+ }
194
+ function isCodeLanguageLoaded(language) {
195
+ const diffedLanguage = getDiffedLanguage(language);
196
+ const langId = diffedLanguage ? diffedLanguage : language;
197
+ try {
198
+ // eslint-disable-next-line no-prototype-builtins
199
+ return langId ? Prism$1.languages.hasOwnProperty(langId) : false;
200
+ } catch (_unused) {
201
+ return false;
202
+ }
203
+ }
204
+ async function loadCodeLanguage(language, editor, codeNodeKey) {
205
+ // NOT IMPLEMENTED
206
+ }
207
+ function getTextContent(token) {
208
+ if (typeof token === 'string') {
209
+ return token;
210
+ } else if (Array.isArray(token)) {
211
+ return token.map(getTextContent).join('');
212
+ } else {
213
+ return getTextContent(token.content);
214
+ }
215
+ }
216
+
217
+ // The following code is extracted/adapted from prismjs v2
218
+ // It will probably be possible to use it directly from prism v2
219
+ // in the future when prismjs v2 is published and Lexical upgrades
220
+ // the prismsjs dependency
221
+ function tokenizeDiffHighlight(tokens, language) {
222
+ const diffLanguage = language;
223
+ const diffGrammar = Prism$1.languages[diffLanguage];
224
+ const env = {
225
+ tokens
226
+ };
227
+ const PREFIXES = Prism$1.languages.diff.PREFIXES;
228
+ for (const token of env.tokens) {
229
+ if (typeof token === 'string' || !(token.type in PREFIXES) || !Array.isArray(token.content)) {
230
+ continue;
231
+ }
232
+ const type = token.type;
233
+ let insertedPrefixes = 0;
234
+ const getPrefixToken = () => {
235
+ insertedPrefixes++;
236
+ return new Prism$1.Token('prefix', PREFIXES[type], type.replace(/^(\w+).*/, '$1'));
237
+ };
238
+ const withoutPrefixes = token.content.filter(t => typeof t === 'string' || t.type !== 'prefix');
239
+ const prefixCount = token.content.length - withoutPrefixes.length;
240
+ const diffTokens = Prism$1.tokenize(getTextContent(withoutPrefixes), diffGrammar);
241
+
242
+ // re-insert prefixes
243
+ // always add a prefix at the start
244
+ diffTokens.unshift(getPrefixToken());
245
+ const LINE_BREAK = /\r\n|\n/g;
246
+ const insertAfterLineBreakString = text => {
247
+ const result = [];
248
+ LINE_BREAK.lastIndex = 0;
249
+ let last = 0;
250
+ let m;
251
+ while (insertedPrefixes < prefixCount && (m = LINE_BREAK.exec(text))) {
252
+ const end = m.index + m[0].length;
253
+ result.push(text.slice(last, end));
254
+ last = end;
255
+ result.push(getPrefixToken());
256
+ }
257
+ if (result.length === 0) {
258
+ return undefined;
259
+ }
260
+ if (last < text.length) {
261
+ result.push(text.slice(last));
262
+ }
263
+ return result;
264
+ };
265
+ const insertAfterLineBreak = toks => {
266
+ for (let i = 0; i < toks.length && insertedPrefixes < prefixCount; i++) {
267
+ const tok = toks[i];
268
+ if (typeof tok === 'string') {
269
+ const inserted = insertAfterLineBreakString(tok);
270
+ if (inserted) {
271
+ toks.splice(i, 1, ...inserted);
272
+ i += inserted.length - 1;
273
+ }
274
+ } else if (typeof tok.content === 'string') {
275
+ const inserted = insertAfterLineBreakString(tok.content);
276
+ if (inserted) {
277
+ tok.content = inserted;
278
+ }
279
+ } else if (Array.isArray(tok.content)) {
280
+ insertAfterLineBreak(tok.content);
281
+ } else {
282
+ insertAfterLineBreak([tok.content]);
283
+ }
284
+ }
285
+ };
286
+ insertAfterLineBreak(diffTokens);
287
+ if (insertedPrefixes < prefixCount) {
288
+ // we are missing the last prefix
289
+ diffTokens.push(getPrefixToken());
290
+ }
291
+ token.content = diffTokens;
292
+ }
293
+ return env.tokens;
294
+ }
295
+ function $getHighlightNodes(codeNode, language) {
296
+ const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
297
+ const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(language);
298
+ const code = codeNode.getTextContent();
299
+ let tokens = Prism$1.tokenize(code, Prism$1.languages[diffLanguageMatch ? 'diff' : language]);
300
+ if (diffLanguageMatch) {
301
+ tokens = tokenizeDiffHighlight(tokens, diffLanguageMatch[1]);
302
+ }
303
+ return $mapTokensToLexicalStructure(tokens);
304
+ }
305
+ function $mapTokensToLexicalStructure(tokens, type) {
306
+ const nodes = [];
307
+ for (const token of tokens) {
308
+ if (typeof token === 'string') {
309
+ const partials = token.split(/(\n|\t)/);
310
+ const partialsLength = partials.length;
311
+ for (let i = 0; i < partialsLength; i++) {
312
+ const part = partials[i];
313
+ if (part === '\n' || part === '\r\n') {
314
+ nodes.push(lexical.$createLineBreakNode());
315
+ } else if (part === '\t') {
316
+ nodes.push(lexical.$createTabNode());
317
+ } else if (part.length > 0) {
318
+ nodes.push(codeCore.$createCodeHighlightNode(part, type));
319
+ }
320
+ }
321
+ } else {
322
+ const {
323
+ content,
324
+ alias
325
+ } = token;
326
+ if (typeof content === 'string') {
327
+ nodes.push(...$mapTokensToLexicalStructure([content], token.type === 'prefix' && typeof alias === 'string' ? alias : token.type));
328
+ } else if (Array.isArray(content)) {
329
+ nodes.push(...$mapTokensToLexicalStructure(content, token.type === 'unchanged' ? undefined : token.type));
330
+ }
331
+ }
332
+ }
333
+ return nodes;
334
+ }
335
+
336
+ const PrismTokenizer = {
337
+ $tokenize(codeNode, language) {
338
+ return $getHighlightNodes(codeNode, language || this.defaultLanguage);
339
+ },
340
+ defaultLanguage: codeCore.DEFAULT_CODE_LANGUAGE,
341
+ tokenize(code, language) {
342
+ return Prism$1.tokenize(code, Prism$1.languages[language || ''] || Prism$1.languages[this.defaultLanguage]);
343
+ }
344
+ };
345
+ function $textNodeTransform(node, editor, tokenizer) {
346
+ // Since CodeNode has flat children structure we only need to check
347
+ // if node's parent is a code node and run highlighting if so
348
+ const parentNode = node.getParent();
349
+ if (codeCore.$isCodeNode(parentNode)) {
350
+ codeNodeTransform(parentNode, editor, tokenizer);
351
+ } else if (codeCore.$isCodeHighlightNode(node)) {
352
+ // When code block converted into paragraph or other element
353
+ // code highlight nodes converted back to normal text
354
+ node.replace(lexical.$createTextNode(node.__text));
355
+ }
356
+ }
357
+ function updateCodeGutter(node, editor) {
358
+ const codeElement = editor.getElementByKey(node.getKey());
359
+ if (codeElement === null) {
360
+ return;
361
+ }
362
+ const children = node.getChildren();
363
+ const childrenLength = children.length;
364
+ // @ts-ignore: internal field
365
+ if (childrenLength === codeElement.__cachedChildrenLength) {
366
+ // Avoid updating the attribute if the children length hasn't changed.
367
+ return;
368
+ }
369
+ // @ts-ignore:: internal field
370
+ codeElement.__cachedChildrenLength = childrenLength;
371
+ let gutter = '1';
372
+ let count = 1;
373
+ for (let i = 0; i < childrenLength; i++) {
374
+ if (lexical.$isLineBreakNode(children[i])) {
375
+ gutter += '\n' + ++count;
376
+ }
377
+ }
378
+ codeElement.setAttribute('data-gutter', gutter);
379
+ }
380
+
381
+ // Using `skipTransforms` to prevent extra transforms since reformatting the code
382
+ // will not affect code block content itself.
383
+ //
384
+ // Using extra cache (`nodesCurrentlyHighlighting`) since both CodeNode and CodeHighlightNode
385
+ // transforms might be called at the same time (e.g. new CodeHighlight node inserted) and
386
+ // in both cases we'll rerun whole reformatting over CodeNode, which is redundant.
387
+ // Especially when pasting code into CodeBlock.
388
+
389
+ const nodesCurrentlyHighlighting = new Set();
390
+ function codeNodeTransform(node, editor, tokenizer) {
391
+ const nodeKey = node.getKey();
392
+ const cacheKey = editor.getKey() + '/' + nodeKey;
393
+
394
+ // When new code block inserted it might not have language selected
395
+ if (node.getLanguage() === undefined) {
396
+ node.setLanguage(tokenizer.defaultLanguage);
397
+ }
398
+ const language = node.getLanguage() || tokenizer.defaultLanguage;
399
+ if (isCodeLanguageLoaded(language)) {
400
+ if (!node.getIsSyntaxHighlightSupported()) {
401
+ node.setIsSyntaxHighlightSupported(true);
402
+ }
403
+ } else {
404
+ if (node.getIsSyntaxHighlightSupported()) {
405
+ node.setIsSyntaxHighlightSupported(false);
406
+ }
407
+ loadCodeLanguage(language, editor, nodeKey);
408
+ return;
409
+ }
410
+ if (nodesCurrentlyHighlighting.has(cacheKey)) {
411
+ return;
412
+ }
413
+ nodesCurrentlyHighlighting.add(cacheKey);
414
+
415
+ // Using nested update call to pass `skipTransforms` since we don't want
416
+ // each individual CodeHighlightNode to be transformed again as it's already
417
+ // in its final state
418
+ editor.update(() => {
419
+ $updateAndRetainSelection(nodeKey, () => {
420
+ const currentNode = lexical.$getNodeByKey(nodeKey);
421
+ if (!codeCore.$isCodeNode(currentNode) || !currentNode.isAttached()) {
422
+ return false;
423
+ }
424
+ //const DIFF_LANGUAGE_REGEX = /^diff-([\w-]+)/i;
425
+ const currentLanguage = currentNode.getLanguage() || tokenizer.defaultLanguage;
426
+ //const diffLanguageMatch = DIFF_LANGUAGE_REGEX.exec(currentLanguage);
427
+
428
+ const highlightNodes = tokenizer.$tokenize(currentNode, currentLanguage);
429
+ const diffRange = getDiffRange(currentNode.getChildren(), highlightNodes);
430
+ const {
431
+ from,
432
+ to,
433
+ nodesForReplacement
434
+ } = diffRange;
435
+ if (from !== to || nodesForReplacement.length) {
436
+ node.splice(from, to - from, nodesForReplacement);
437
+ return true;
438
+ }
439
+ return false;
440
+ });
441
+ }, {
442
+ onUpdate: () => {
443
+ nodesCurrentlyHighlighting.delete(cacheKey);
444
+ },
445
+ skipTransforms: true
446
+ });
447
+ }
448
+
449
+ // Wrapping update function into selection retainer, that tries to keep cursor at the same
450
+ // position as before.
451
+ function $updateAndRetainSelection(nodeKey, updateFn) {
452
+ const node = lexical.$getNodeByKey(nodeKey);
453
+ if (!codeCore.$isCodeNode(node) || !node.isAttached()) {
454
+ return;
455
+ }
456
+ const selection = lexical.$getSelection();
457
+ // If it's not range selection (or null selection) there's no need to change it,
458
+ // but we can still run highlighting logic
459
+ if (!lexical.$isRangeSelection(selection)) {
460
+ updateFn();
461
+ return;
462
+ }
463
+ const anchor = selection.anchor;
464
+ const anchorOffset = anchor.offset;
465
+ const isNewLineAnchor = anchor.type === 'element' && lexical.$isLineBreakNode(node.getChildAtIndex(anchor.offset - 1));
466
+ let textOffset = 0;
467
+
468
+ // Calculating previous text offset (all text node prior to anchor + anchor own text offset)
469
+ if (!isNewLineAnchor) {
470
+ const anchorNode = anchor.getNode();
471
+ textOffset = anchorOffset + anchorNode.getPreviousSiblings().reduce((offset, _node) => {
472
+ return offset + _node.getTextContentSize();
473
+ }, 0);
474
+ }
475
+ const hasChanges = updateFn();
476
+ if (!hasChanges) {
477
+ return;
478
+ }
479
+
480
+ // Non-text anchors only happen for line breaks, otherwise
481
+ // selection will be within text node (code highlight node)
482
+ if (isNewLineAnchor) {
483
+ anchor.getNode().select(anchorOffset, anchorOffset);
484
+ return;
485
+ }
486
+
487
+ // If it was non-element anchor then we walk through child nodes
488
+ // and looking for a position of original text offset
489
+ node.getChildren().some(_node => {
490
+ const isText = lexical.$isTextNode(_node);
491
+ if (isText || lexical.$isLineBreakNode(_node)) {
492
+ const textContentSize = _node.getTextContentSize();
493
+ if (isText && textContentSize >= textOffset) {
494
+ _node.select(textOffset, textOffset);
495
+ return true;
496
+ }
497
+ textOffset -= textContentSize;
498
+ }
499
+ return false;
500
+ });
501
+ }
502
+
503
+ // Finds minimal diff range between two nodes lists. It returns from/to range boundaries of prevNodes
504
+ // that needs to be replaced with `nodes` (subset of nextNodes) to make prevNodes equal to nextNodes.
505
+ function getDiffRange(prevNodes, nextNodes) {
506
+ let leadingMatch = 0;
507
+ while (leadingMatch < prevNodes.length) {
508
+ if (!isEqual(prevNodes[leadingMatch], nextNodes[leadingMatch])) {
509
+ break;
510
+ }
511
+ leadingMatch++;
512
+ }
513
+ const prevNodesLength = prevNodes.length;
514
+ const nextNodesLength = nextNodes.length;
515
+ const maxTrailingMatch = Math.min(prevNodesLength, nextNodesLength) - leadingMatch;
516
+ let trailingMatch = 0;
517
+ while (trailingMatch < maxTrailingMatch) {
518
+ trailingMatch++;
519
+ if (!isEqual(prevNodes[prevNodesLength - trailingMatch], nextNodes[nextNodesLength - trailingMatch])) {
520
+ trailingMatch--;
521
+ break;
522
+ }
523
+ }
524
+ const from = leadingMatch;
525
+ const to = prevNodesLength - trailingMatch;
526
+ const nodesForReplacement = nextNodes.slice(leadingMatch, nextNodesLength - trailingMatch);
527
+ return {
528
+ from,
529
+ nodesForReplacement,
530
+ to
531
+ };
532
+ }
533
+ function isEqual(nodeA, nodeB) {
534
+ // Only checking for code highlight nodes, tabs and linebreaks. If it's regular text node
535
+ // returning false so that it's transformed into code highlight node
536
+ return codeCore.$isCodeHighlightNode(nodeA) && codeCore.$isCodeHighlightNode(nodeB) && nodeA.__text === nodeB.__text && nodeA.__highlightType === nodeB.__highlightType || lexical.$isTabNode(nodeA) && lexical.$isTabNode(nodeB) || lexical.$isLineBreakNode(nodeA) && lexical.$isLineBreakNode(nodeB);
537
+ }
538
+
539
+ /**
540
+ * Returns a boolean.
541
+ * Check that the selection span is within a single CodeNode.
542
+ * This is used to guard against executing handlers that can only be
543
+ * applied in a single CodeNode context
544
+ */
545
+ function $isSelectionInCode(selection) {
546
+ if (!lexical.$isRangeSelection(selection)) {
547
+ return false;
548
+ }
549
+ const anchorNode = selection.anchor.getNode();
550
+ const maybeAnchorCodeNode = codeCore.$isCodeNode(anchorNode) ? anchorNode : anchorNode.getParent();
551
+ const focusNode = selection.focus.getNode();
552
+ const maybeFocusCodeNode = codeCore.$isCodeNode(focusNode) ? focusNode : focusNode.getParent();
553
+ return codeCore.$isCodeNode(maybeAnchorCodeNode) && maybeAnchorCodeNode.is(maybeFocusCodeNode);
554
+ }
555
+
556
+ /**
557
+ * Returns an Array of code lines
558
+ * Take the sequence of LineBreakNode | TabNode | CodeHighlightNode forming
559
+ * the selection and split it by LineBreakNode.
560
+ * If the selection ends at the start of the last line, it is considered empty.
561
+ * Empty lines are discarded.
562
+ */
563
+ function $getCodeLines(selection) {
564
+ const nodes = selection.getNodes();
565
+ const lines = [];
566
+ if (nodes.length === 1 && codeCore.$isCodeNode(nodes[0])) {
567
+ return lines;
568
+ }
569
+ let lastLine = [];
570
+ for (let i = 0; i < nodes.length; i++) {
571
+ const node = nodes[i];
572
+ if (!(codeCore.$isCodeHighlightNode(node) || lexical.$isTabNode(node) || lexical.$isLineBreakNode(node))) {
573
+ formatDevErrorMessage(`Expected selection to be inside CodeBlock and consisting of CodeHighlightNode, TabNode and LineBreakNode`);
574
+ }
575
+ if (lexical.$isLineBreakNode(node)) {
576
+ if (lastLine.length > 0) {
577
+ lines.push(lastLine);
578
+ lastLine = [];
579
+ }
580
+ } else {
581
+ lastLine.push(node);
582
+ }
583
+ }
584
+ if (lastLine.length > 0) {
585
+ const selectionEnd = selection.isBackward() ? selection.anchor : selection.focus;
586
+
587
+ // Discard the last line if the selection ends exactly at the
588
+ // start of the line (no real selection)
589
+ const lastPoint = lexical.$createPoint(lastLine[0].getKey(), 0, 'text');
590
+ if (!selectionEnd.is(lastPoint)) {
591
+ lines.push(lastLine);
592
+ }
593
+ }
594
+ return lines;
595
+ }
596
+ function $handleTab(shiftKey) {
597
+ const selection = lexical.$getSelection();
598
+ if (!lexical.$isRangeSelection(selection) || !$isSelectionInCode(selection)) {
599
+ return null;
600
+ }
601
+ const indentOrOutdent = !shiftKey ? lexical.INDENT_CONTENT_COMMAND : lexical.OUTDENT_CONTENT_COMMAND;
602
+ const tabOrOutdent = !shiftKey ? lexical.INSERT_TAB_COMMAND : lexical.OUTDENT_CONTENT_COMMAND;
603
+ const anchor = selection.anchor;
604
+ const focus = selection.focus;
605
+
606
+ // 1. early decision when there is no real selection
607
+ if (anchor.is(focus)) {
608
+ return tabOrOutdent;
609
+ }
610
+
611
+ // 2. If only empty lines or multiple non-empty lines are selected: indent/outdent
612
+ const codeLines = $getCodeLines(selection);
613
+ if (codeLines.length !== 1) {
614
+ return indentOrOutdent;
615
+ }
616
+ const codeLine = codeLines[0];
617
+ const codeLineLength = codeLine.length;
618
+ if (!(codeLineLength !== 0)) {
619
+ formatDevErrorMessage(`$getCodeLines only extracts non-empty lines`);
620
+ } // Take into account the direction of the selection
621
+ let selectionFirst;
622
+ let selectionLast;
623
+ if (selection.isBackward()) {
624
+ selectionFirst = focus;
625
+ selectionLast = anchor;
626
+ } else {
627
+ selectionFirst = anchor;
628
+ selectionLast = focus;
629
+ }
630
+
631
+ // find boundary elements of the line
632
+ // since codeLine only contains TabNode | CodeHighlightNode
633
+ // the result of these functions should is of Type TabNode | CodeHighlightNode
634
+ const firstOfLine = codeCore.$getFirstCodeNodeOfLine(codeLine[0]);
635
+ const lastOfLine = codeCore.$getLastCodeNodeOfLine(codeLine[0]);
636
+ const anchorOfLine = lexical.$createPoint(firstOfLine.getKey(), 0, 'text');
637
+ const focusOfLine = lexical.$createPoint(lastOfLine.getKey(), lastOfLine.getTextContentSize(), 'text');
638
+
639
+ // 3. multiline because selection started strictly before the line
640
+ if (selectionFirst.isBefore(anchorOfLine)) {
641
+ return indentOrOutdent;
642
+ }
643
+
644
+ // 4. multiline because the selection stops strictly after the line
645
+ if (focusOfLine.isBefore(selectionLast)) {
646
+ return indentOrOutdent;
647
+ }
648
+
649
+ // The selection if within the line.
650
+ // 4. If it does not touch both borders, it needs a tab
651
+ if (anchorOfLine.isBefore(selectionFirst) || selectionLast.isBefore(focusOfLine)) {
652
+ return tabOrOutdent;
653
+ }
654
+
655
+ // 5. Selection is matching a full line on non-empty code
656
+ return indentOrOutdent;
657
+ }
658
+ function $handleMultilineIndent(type) {
659
+ const selection = lexical.$getSelection();
660
+ if (!lexical.$isRangeSelection(selection) || !$isSelectionInCode(selection)) {
661
+ return false;
662
+ }
663
+ const codeLines = $getCodeLines(selection);
664
+ const codeLinesLength = codeLines.length;
665
+
666
+ // Special Indent case
667
+ // Selection is collapsed at the beginning of a line
668
+ if (codeLinesLength === 0 && selection.isCollapsed()) {
669
+ if (type === lexical.INDENT_CONTENT_COMMAND) {
670
+ selection.insertNodes([lexical.$createTabNode()]);
671
+ }
672
+ return true;
673
+ }
674
+
675
+ // Special Indent case
676
+ // Selection is matching only one LineBreak
677
+ if (codeLinesLength === 0 && type === lexical.INDENT_CONTENT_COMMAND && selection.getTextContent() === '\n') {
678
+ const tabNode = lexical.$createTabNode();
679
+ const lineBreakNode = lexical.$createLineBreakNode();
680
+ const direction = selection.isBackward() ? 'previous' : 'next';
681
+ selection.insertNodes([tabNode, lineBreakNode]);
682
+ lexical.$setSelectionFromCaretRange(lexical.$getCaretRangeInDirection(lexical.$getCaretRange(lexical.$getTextPointCaret(tabNode, 'next', 0), lexical.$normalizeCaret(lexical.$getSiblingCaret(lineBreakNode, 'next'))), direction));
683
+ return true;
684
+ }
685
+
686
+ // Indent Non Empty Lines
687
+ for (let i = 0; i < codeLinesLength; i++) {
688
+ const line = codeLines[i];
689
+ // a line here is never empty
690
+ if (line.length > 0) {
691
+ let firstOfLine = line[0];
692
+
693
+ // make sure to consider the first node on the first line
694
+ // because the line might not be fully selected
695
+ if (i === 0) {
696
+ firstOfLine = codeCore.$getFirstCodeNodeOfLine(firstOfLine);
697
+ }
698
+ if (type === lexical.INDENT_CONTENT_COMMAND) {
699
+ const tabNode = lexical.$createTabNode();
700
+ firstOfLine.insertBefore(tabNode);
701
+ // First real code line may need selection adjustment
702
+ // when firstOfLine is at the selection boundary
703
+ if (i === 0) {
704
+ const anchorKey = selection.isBackward() ? 'focus' : 'anchor';
705
+ const anchorLine = lexical.$createPoint(firstOfLine.getKey(), 0, 'text');
706
+ if (selection[anchorKey].is(anchorLine)) {
707
+ selection[anchorKey].set(tabNode.getKey(), 0, 'text');
708
+ }
709
+ }
710
+ } else if (lexical.$isTabNode(firstOfLine)) {
711
+ firstOfLine.remove();
712
+ }
713
+ }
714
+ }
715
+ return true;
716
+ }
717
+ function $handleShiftLines(type, event) {
718
+ // We only care about the alt+arrow keys
719
+ const selection = lexical.$getSelection();
720
+ if (!lexical.$isRangeSelection(selection)) {
721
+ return false;
722
+ }
723
+
724
+ // I'm not quite sure why, but it seems like calling anchor.getNode() collapses the selection here
725
+ // So first, get the anchor and the focus, then get their nodes
726
+ const {
727
+ anchor,
728
+ focus
729
+ } = selection;
730
+ const anchorOffset = anchor.offset;
731
+ const focusOffset = focus.offset;
732
+ const anchorNode = anchor.getNode();
733
+ const focusNode = focus.getNode();
734
+ const arrowIsUp = type === lexical.KEY_ARROW_UP_COMMAND;
735
+
736
+ // Ensure the selection is within the codeblock
737
+ if (!$isSelectionInCode(selection) || !(codeCore.$isCodeHighlightNode(anchorNode) || lexical.$isTabNode(anchorNode)) || !(codeCore.$isCodeHighlightNode(focusNode) || lexical.$isTabNode(focusNode))) {
738
+ return false;
739
+ }
740
+ if (!event.altKey) {
741
+ // Handle moving selection out of the code block, given there are no
742
+ // siblings that can natively take the selection.
743
+ if (selection.isCollapsed()) {
744
+ const codeNode = anchorNode.getParentOrThrow();
745
+ if (arrowIsUp && anchorOffset === 0 && anchorNode.getPreviousSibling() === null) {
746
+ const codeNodeSibling = codeNode.getPreviousSibling();
747
+ if (codeNodeSibling === null) {
748
+ codeNode.selectPrevious();
749
+ event.preventDefault();
750
+ return true;
751
+ }
752
+ } else if (!arrowIsUp && anchorOffset === anchorNode.getTextContentSize() && anchorNode.getNextSibling() === null) {
753
+ const codeNodeSibling = codeNode.getNextSibling();
754
+ if (codeNodeSibling === null) {
755
+ codeNode.selectNext();
756
+ event.preventDefault();
757
+ return true;
758
+ }
759
+ }
760
+ }
761
+ return false;
762
+ }
763
+ let start;
764
+ let end;
765
+ if (anchorNode.isBefore(focusNode)) {
766
+ start = codeCore.$getFirstCodeNodeOfLine(anchorNode);
767
+ end = codeCore.$getLastCodeNodeOfLine(focusNode);
768
+ } else {
769
+ start = codeCore.$getFirstCodeNodeOfLine(focusNode);
770
+ end = codeCore.$getLastCodeNodeOfLine(anchorNode);
771
+ }
772
+ if (start == null || end == null) {
773
+ return false;
774
+ }
775
+ const range = start.getNodesBetween(end);
776
+ for (let i = 0; i < range.length; i++) {
777
+ const node = range[i];
778
+ if (!codeCore.$isCodeHighlightNode(node) && !lexical.$isTabNode(node) && !lexical.$isLineBreakNode(node)) {
779
+ return false;
780
+ }
781
+ }
782
+
783
+ // After this point, we know the selection is within the codeblock. We may not be able to
784
+ // actually move the lines around, but we want to return true either way to prevent
785
+ // the event's default behavior
786
+ event.preventDefault();
787
+ event.stopPropagation(); // required to stop cursor movement under Firefox
788
+
789
+ const linebreak = arrowIsUp ? start.getPreviousSibling() : end.getNextSibling();
790
+ if (!lexical.$isLineBreakNode(linebreak)) {
791
+ return true;
792
+ }
793
+ const sibling = arrowIsUp ? linebreak.getPreviousSibling() : linebreak.getNextSibling();
794
+ if (sibling == null) {
795
+ return true;
796
+ }
797
+ const maybeInsertionPoint = codeCore.$isCodeHighlightNode(sibling) || lexical.$isTabNode(sibling) || lexical.$isLineBreakNode(sibling) ? arrowIsUp ? codeCore.$getFirstCodeNodeOfLine(sibling) : codeCore.$getLastCodeNodeOfLine(sibling) : null;
798
+ let insertionPoint = maybeInsertionPoint != null ? maybeInsertionPoint : sibling;
799
+ linebreak.remove();
800
+ range.forEach(node => node.remove());
801
+ if (type === lexical.KEY_ARROW_UP_COMMAND) {
802
+ range.forEach(node => insertionPoint.insertBefore(node));
803
+ insertionPoint.insertBefore(linebreak);
804
+ } else {
805
+ insertionPoint.insertAfter(linebreak);
806
+ insertionPoint = linebreak;
807
+ range.forEach(node => {
808
+ insertionPoint.insertAfter(node);
809
+ insertionPoint = node;
810
+ });
811
+ }
812
+ selection.setTextNodeRange(anchorNode, anchorOffset, focusNode, focusOffset);
813
+ return true;
814
+ }
815
+ function $handleMoveTo(type, event) {
816
+ const selection = lexical.$getSelection();
817
+ if (!lexical.$isRangeSelection(selection)) {
818
+ return false;
819
+ }
820
+ const {
821
+ anchor,
822
+ focus
823
+ } = selection;
824
+ const anchorNode = anchor.getNode();
825
+ const focusNode = focus.getNode();
826
+ const isMoveToStart = type === lexical.MOVE_TO_START;
827
+
828
+ // Ensure the selection is within the codeblock
829
+ if (!$isSelectionInCode(selection) || !(codeCore.$isCodeHighlightNode(anchorNode) || lexical.$isTabNode(anchorNode)) || !(codeCore.$isCodeHighlightNode(focusNode) || lexical.$isTabNode(focusNode))) {
830
+ return false;
831
+ }
832
+ const focusLineNode = focusNode;
833
+ const direction = codeCore.$getCodeLineDirection(focusLineNode);
834
+ const moveToStart = direction === 'rtl' ? !isMoveToStart : isMoveToStart;
835
+ if (moveToStart) {
836
+ const start = codeCore.$getStartOfCodeInLine(focusLineNode, focus.offset);
837
+ if (start !== null) {
838
+ const {
839
+ node,
840
+ offset
841
+ } = start;
842
+ if (lexical.$isLineBreakNode(node)) {
843
+ node.selectNext(0, 0);
844
+ } else {
845
+ selection.setTextNodeRange(node, offset, node, offset);
846
+ }
847
+ } else {
848
+ focusLineNode.getParentOrThrow().selectStart();
849
+ }
850
+ } else {
851
+ const node = codeCore.$getEndOfCodeInLine(focusLineNode);
852
+ node.select();
853
+ }
854
+ event.preventDefault();
855
+ event.stopPropagation();
856
+ return true;
857
+ }
858
+ function registerCodeHighlighting(editor, tokenizer) {
859
+ if (!editor.hasNodes([codeCore.CodeNode, codeCore.CodeHighlightNode])) {
860
+ throw new Error('CodeHighlightPlugin: CodeNode or CodeHighlightNode not registered on editor');
861
+ }
862
+ if (tokenizer == null) {
863
+ tokenizer = PrismTokenizer;
864
+ }
865
+ const registrations = [];
866
+
867
+ // Only register the mutation listener if not in headless mode
868
+ if (editor._headless !== true) {
869
+ registrations.push(editor.registerMutationListener(codeCore.CodeNode, mutations => {
870
+ editor.getEditorState().read(() => {
871
+ for (const [key, type] of mutations) {
872
+ if (type !== 'destroyed') {
873
+ const node = lexical.$getNodeByKey(key);
874
+ if (node !== null) {
875
+ updateCodeGutter(node, editor);
876
+ }
877
+ }
878
+ }
879
+ });
880
+ }, {
881
+ skipInitialization: false
882
+ }));
883
+ }
884
+
885
+ // Add the rest of the registrations
886
+ registrations.push(editor.registerNodeTransform(codeCore.CodeNode, node => codeNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(lexical.TextNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerNodeTransform(codeCore.CodeHighlightNode, node => $textNodeTransform(node, editor, tokenizer)), editor.registerCommand(lexical.KEY_TAB_COMMAND, event => {
887
+ const command = $handleTab(event.shiftKey);
888
+ if (command === null) {
889
+ return false;
890
+ }
891
+ event.preventDefault();
892
+ editor.dispatchCommand(command, undefined);
893
+ return true;
894
+ }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.INSERT_TAB_COMMAND, () => {
895
+ const selection = lexical.$getSelection();
896
+ if (!$isSelectionInCode(selection)) {
897
+ return false;
898
+ }
899
+ lexical.$insertNodes([lexical.$createTabNode()]);
900
+ return true;
901
+ }, 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 => {
902
+ const selection = lexical.$getSelection();
903
+ if (!lexical.$isRangeSelection(selection) || !$isSelectionInCode(selection)) {
904
+ return false;
905
+ }
906
+ const firstNode = lexical.$getRoot().getFirstDescendant();
907
+ const {
908
+ anchor
909
+ } = selection;
910
+ const anchorNode = anchor.getNode();
911
+ if (firstNode && anchorNode && firstNode.getKey() === anchorNode.getKey()) {
912
+ return false;
913
+ }
914
+ return $handleShiftLines(lexical.KEY_ARROW_UP_COMMAND, event);
915
+ }, lexical.COMMAND_PRIORITY_LOW), editor.registerCommand(lexical.KEY_ARROW_DOWN_COMMAND, event => {
916
+ const selection = lexical.$getSelection();
917
+ if (!lexical.$isRangeSelection(selection) || !$isSelectionInCode(selection)) {
918
+ return false;
919
+ }
920
+ const lastNode = lexical.$getRoot().getLastDescendant();
921
+ const {
922
+ anchor
923
+ } = selection;
924
+ const anchorNode = anchor.getNode();
925
+ if (lastNode && anchorNode && lastNode.getKey() === anchorNode.getKey()) {
926
+ return false;
927
+ }
928
+ return $handleShiftLines(lexical.KEY_ARROW_DOWN_COMMAND, event);
929
+ }, 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));
930
+ return lexical.mergeRegister(...registrations);
931
+ }
932
+
933
+ /**
934
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
935
+ *
936
+ * This source code is licensed under the MIT license found in the
937
+ * LICENSE file in the root directory of this source tree.
938
+ *
939
+ */
940
+
941
+ exports.CODE_LANGUAGE_FRIENDLY_NAME_MAP = CODE_LANGUAGE_FRIENDLY_NAME_MAP;
942
+ exports.CODE_LANGUAGE_MAP = CODE_LANGUAGE_MAP;
943
+ exports.PrismTokenizer = PrismTokenizer;
944
+ exports.getCodeLanguageOptions = getCodeLanguageOptions;
945
+ exports.getCodeLanguages = getCodeLanguages;
946
+ exports.getCodeThemeOptions = getCodeThemeOptions;
947
+ exports.getLanguageFriendlyName = getLanguageFriendlyName;
948
+ exports.isCodeLanguageLoaded = isCodeLanguageLoaded;
949
+ exports.loadCodeLanguage = loadCodeLanguage;
950
+ exports.normalizeCodeLanguage = normalizeCodeLanguage;
951
+ exports.registerCodeHighlighting = registerCodeHighlighting;