Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@lexical/code

Package Overview
Dependencies
Maintainers
6
Versions
195
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lexical/code - npm Package Compare versions

Comparing version 0.3.8 to 0.3.9

CodeHighlighter.d.ts

76

index.d.ts

@@ -8,74 +8,4 @@ /**

*/
import type { DOMConversionMap, EditorConfig, LexicalEditor, LexicalNode, NodeKey, ParagraphNode, RangeSelection, SerializedElementNode, SerializedTextNode, Spread } from 'lexical';
import 'prismjs/components/prism-clike';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-markdown';
import 'prismjs/components/prism-c';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-objectivec';
import 'prismjs/components/prism-sql';
import 'prismjs/components/prism-python';
import 'prismjs/components/prism-rust';
import 'prismjs/components/prism-swift';
import { ElementNode, TextNode } from 'lexical';
declare type SerializedCodeNode = Spread<{
language: string | null | undefined;
type: 'code';
version: 1;
}, SerializedElementNode>;
declare type SerializedCodeHighlightNode = Spread<{
highlightType: string | null | undefined;
type: 'code-highlight';
version: 1;
}, SerializedTextNode>;
export declare const CODE_LANGUAGE_FRIENDLY_NAME_MAP: Record<string, string>;
export declare const CODE_LANGUAGE_MAP: Record<string, string>;
export declare function getLanguageFriendlyName(lang: string): string;
export declare const getDefaultCodeLanguage: () => string;
export declare const getCodeLanguages: () => Array<string>;
export declare class CodeHighlightNode extends TextNode {
__highlightType: string | null | undefined;
constructor(text: string, highlightType?: string | null | undefined, key?: NodeKey);
static getType(): string;
static clone(node: CodeHighlightNode): CodeHighlightNode;
getHighlightType(): string | null | undefined;
createDOM(config: EditorConfig): HTMLElement;
updateDOM(prevNode: CodeHighlightNode, dom: HTMLElement, config: EditorConfig): boolean;
static importJSON(serializedNode: SerializedCodeHighlightNode): CodeHighlightNode;
exportJSON(): SerializedCodeHighlightNode;
setFormat(format: number): this;
}
export declare function $createCodeHighlightNode(text: string, highlightType?: string | null | undefined): CodeHighlightNode;
export declare function $isCodeHighlightNode(node: LexicalNode | CodeHighlightNode | null | undefined): node is CodeHighlightNode;
export declare class CodeNode extends ElementNode {
__language: string | null | undefined;
static getType(): string;
static clone(node: CodeNode): CodeNode;
constructor(language?: string | null | undefined, key?: NodeKey);
createDOM(config: EditorConfig): HTMLElement;
updateDOM(prevNode: CodeNode, dom: HTMLElement): boolean;
static importDOM(): DOMConversionMap | null;
static importJSON(serializedNode: SerializedCodeNode): CodeNode;
exportJSON(): SerializedCodeNode;
insertNewAfter(selection: RangeSelection): null | ParagraphNode | CodeHighlightNode;
canInsertTab(): boolean;
canIndent(): false;
collapseAtStart(): true;
setLanguage(language: string): void;
getLanguage(): string | null | undefined;
}
export declare function $createCodeNode(language?: string | null | undefined): CodeNode;
export declare function $isCodeNode(node: LexicalNode | null | undefined): node is CodeNode;
export declare function getFirstCodeHighlightNodeOfLine(anchor: LexicalNode): CodeHighlightNode | null | undefined;
export declare function getLastCodeHighlightNodeOfLine(anchor: LexicalNode): CodeHighlightNode | null | undefined;
export declare function getStartOfCodeInLine(anchor: LexicalNode): {
node: TextNode | null;
offset: number;
};
export declare function getEndOfCodeInLine(anchor: LexicalNode): {
node: TextNode | null;
offset: number;
};
export declare function registerCodeHighlighting(editor: LexicalEditor): () => void;
export {};
export { getEndOfCodeInLine, getStartOfCodeInLine, registerCodeHighlighting, } from './CodeHighlighter';
export { $createCodeHighlightNode, $isCodeHighlightNode, CODE_LANGUAGE_FRIENDLY_NAME_MAP, CODE_LANGUAGE_MAP, CodeHighlightNode, DEFAULT_CODE_LANGUAGE, getCodeLanguages, getDefaultCodeLanguage, getFirstCodeHighlightNodeOfLine, getLanguageFriendlyName, getLastCodeHighlightNodeOfLine, normalizeCodeLang, } from './CodeHighlightNode';
export { $createCodeNode, $isCodeNode, CodeNode } from './CodeNode';

@@ -23,2 +23,3 @@ /**

var lexical = require('lexical');
var code = require('@lexical/code');

@@ -32,367 +33,3 @@ /**

*/
const DEFAULT_CODE_LANGUAGE = 'javascript';
const CODE_LANGUAGE_FRIENDLY_NAME_MAP = {
c: 'C',
clike: 'C-like',
css: 'CSS',
html: 'HTML',
js: 'JavaScript',
markdown: 'Markdown',
objc: 'Objective-C',
plain: 'Plain Text',
py: 'Python',
rust: 'Rust',
sql: 'SQL',
swift: 'Swift',
xml: 'XML'
};
const CODE_LANGUAGE_MAP = {
javascript: 'js',
md: 'markdown',
plaintext: 'plain',
python: 'py',
text: 'plain'
};
function getLanguageFriendlyName(lang) {
const _lang = CODE_LANGUAGE_MAP[lang] || lang;
return CODE_LANGUAGE_FRIENDLY_NAME_MAP[_lang] || _lang;
}
const mapToPrismLanguage = language => {
// eslint-disable-next-line no-prototype-builtins
return language != null && Prism.languages.hasOwnProperty(language) ? language : undefined;
};
const getDefaultCodeLanguage = () => DEFAULT_CODE_LANGUAGE;
const getCodeLanguages = () => Object.keys(Prism.languages).filter( // Prism has several language helpers mixed into languages object
// so filtering them out here to get langs list
language => typeof Prism.languages[language] !== 'function').sort();
class CodeHighlightNode extends lexical.TextNode {
constructor(text, highlightType, key) {
super(text, key);
this.__highlightType = highlightType;
}
static getType() {
return 'code-highlight';
}
static clone(node) {
return new CodeHighlightNode(node.__text, node.__highlightType || undefined, node.__key);
}
getHighlightType() {
const self = this.getLatest();
return self.__highlightType;
}
createDOM(config) {
const element = super.createDOM(config);
const className = getHighlightThemeClass(config.theme, this.__highlightType);
utils.addClassNamesToElement(element, className);
return element;
}
updateDOM(prevNode, dom, config) {
const update = super.updateDOM(prevNode, dom, config);
const prevClassName = getHighlightThemeClass(config.theme, prevNode.__highlightType);
const nextClassName = getHighlightThemeClass(config.theme, this.__highlightType);
if (prevClassName !== nextClassName) {
if (prevClassName) {
utils.removeClassNamesFromElement(dom, prevClassName);
}
if (nextClassName) {
utils.addClassNamesToElement(dom, nextClassName);
}
}
return update;
}
static importJSON(serializedNode) {
const node = $createCodeHighlightNode(serializedNode.text, serializedNode.highlightType);
node.setFormat(serializedNode.format);
node.setDetail(serializedNode.detail);
node.setMode(serializedNode.mode);
node.setStyle(serializedNode.style);
return node;
}
exportJSON() {
return { ...super.exportJSON(),
highlightType: this.getHighlightType(),
type: 'code-highlight',
version: 1
};
} // Prevent formatting (bold, underline, etc)
setFormat(format) {
return this;
}
}
function getHighlightThemeClass(theme, highlightType) {
return highlightType && theme && theme.codeHighlight && theme.codeHighlight[highlightType];
}
function $createCodeHighlightNode(text, highlightType) {
return new CodeHighlightNode(text, highlightType);
}
function $isCodeHighlightNode(node) {
return node instanceof CodeHighlightNode;
}
const LANGUAGE_DATA_ATTRIBUTE = 'data-highlight-language';
class CodeNode extends lexical.ElementNode {
static getType() {
return 'code';
}
static clone(node) {
return new CodeNode(node.__language, node.__key);
}
constructor(language, key) {
super(key);
this.__language = mapToPrismLanguage(language);
} // View
createDOM(config) {
const element = document.createElement('code');
utils.addClassNamesToElement(element, config.theme.code);
element.setAttribute('spellcheck', 'false');
const language = this.getLanguage();
if (language) {
element.setAttribute(LANGUAGE_DATA_ATTRIBUTE, language);
}
return element;
}
updateDOM(prevNode, dom) {
const language = this.__language;
const prevLanguage = prevNode.__language;
if (language) {
if (language !== prevLanguage) {
dom.setAttribute(LANGUAGE_DATA_ATTRIBUTE, language);
}
} else if (prevLanguage) {
dom.removeAttribute(LANGUAGE_DATA_ATTRIBUTE);
}
return false;
}
static importDOM() {
return {
// Typically <pre> is used for code blocks, and <code> for inline code styles
// but if it's a multi line <code> we'll create a block. Pass through to
// inline format handled by TextNode otherwise
code: node => {
const isMultiLine = node.textContent != null && /\r?\n/.test(node.textContent);
return isMultiLine ? {
conversion: convertPreElement,
priority: 1
} : null;
},
div: node => ({
conversion: convertDivElement,
priority: 1
}),
pre: node => ({
conversion: convertPreElement,
priority: 0
}),
table: node => {
const table = node; // domNode is a <table> since we matched it by nodeName
if (isGitHubCodeTable(table)) {
return {
conversion: convertTableElement,
priority: 4
};
}
return null;
},
td: node => {
// element is a <td> since we matched it by nodeName
const td = node;
const table = td.closest('table');
if (isGitHubCodeCell(td)) {
return {
conversion: convertTableCellElement,
priority: 4
};
}
if (table && isGitHubCodeTable(table)) {
// Return a no-op if it's a table cell in a code table, but not a code line.
// Otherwise it'll fall back to the T
return {
conversion: convertCodeNoop,
priority: 4
};
}
return null;
},
tr: node => {
// element is a <tr> since we matched it by nodeName
const tr = node;
const table = tr.closest('table');
if (table && isGitHubCodeTable(table)) {
return {
conversion: convertCodeNoop,
priority: 4
};
}
return null;
}
};
}
static importJSON(serializedNode) {
const node = $createCodeNode(serializedNode.language);
node.setFormat(serializedNode.format);
node.setIndent(serializedNode.indent);
node.setDirection(serializedNode.direction);
return node;
}
exportJSON() {
return { ...super.exportJSON(),
language: this.getLanguage(),
type: 'code',
version: 1
};
} // Mutation
insertNewAfter(selection) {
const children = this.getChildren();
const childrenLength = children.length;
if (childrenLength >= 2 && children[childrenLength - 1].getTextContent() === '\n' && children[childrenLength - 2].getTextContent() === '\n' && selection.isCollapsed() && selection.anchor.key === this.__key && selection.anchor.offset === childrenLength) {
children[childrenLength - 1].remove();
children[childrenLength - 2].remove();
const newElement = lexical.$createParagraphNode();
this.insertAfter(newElement);
return newElement;
} // If the selection is within the codeblock, find all leading tabs and
// spaces of the current line. Create a new line that has all those
// tabs and spaces, such that leading indentation is preserved.
const anchor = selection.anchor.getNode();
const firstNode = getFirstCodeHighlightNodeOfLine(anchor);
if (firstNode != null) {
let leadingWhitespace = 0;
const firstNodeText = firstNode.getTextContent();
while (leadingWhitespace < firstNodeText.length && /[\t ]/.test(firstNodeText[leadingWhitespace])) {
leadingWhitespace += 1;
}
if (leadingWhitespace > 0) {
const whitespace = firstNodeText.substring(0, leadingWhitespace);
const indentedChild = $createCodeHighlightNode(whitespace);
anchor.insertAfter(indentedChild);
selection.insertNodes([lexical.$createLineBreakNode()]);
indentedChild.select();
return indentedChild;
}
}
return null;
}
canInsertTab() {
const selection = lexical.$getSelection();
if (!lexical.$isRangeSelection(selection) || !selection.isCollapsed()) {
return false;
}
return true;
}
canIndent() {
return false;
}
collapseAtStart() {
const paragraph = lexical.$createParagraphNode();
const children = this.getChildren();
children.forEach(child => paragraph.append(child));
this.replace(paragraph);
return true;
}
setLanguage(language) {
const writable = this.getWritable();
writable.__language = mapToPrismLanguage(language);
}
getLanguage() {
return this.getLatest().__language;
}
}
function $createCodeNode(language) {
return new CodeNode(language);
}
function $isCodeNode(node) {
return node instanceof CodeNode;
}
function getFirstCodeHighlightNodeOfLine(anchor) {
let currentNode = null;
const previousSiblings = anchor.getPreviousSiblings();
previousSiblings.push(anchor);
while (previousSiblings.length > 0) {
const node = previousSiblings.pop();
if ($isCodeHighlightNode(node)) {
currentNode = node;
}
if (lexical.$isLineBreakNode(node)) {
break;
}
}
return currentNode;
}
function getLastCodeHighlightNodeOfLine(anchor) {
let currentNode = null;
const nextSiblings = anchor.getNextSiblings();
nextSiblings.unshift(anchor);
while (nextSiblings.length > 0) {
const node = nextSiblings.shift();
if ($isCodeHighlightNode(node)) {
currentNode = node;
}
if (lexical.$isLineBreakNode(node)) {
break;
}
}
return currentNode;
}
function isSpaceOrTabChar(char) {

@@ -438,3 +75,3 @@ return char === ' ' || char === '\t';

if ($isCodeHighlightNode(node)) {
if (code.$isCodeHighlightNode(node)) {
const text = node.getTextContent();

@@ -460,3 +97,3 @@ const offset = findFirstNotSpaceOrTabCharAtText(text, true);

if ($isCodeHighlightNode(node)) {
if (code.$isCodeHighlightNode(node)) {
const text = node.getTextContent();

@@ -492,3 +129,3 @@ const offset = findFirstNotSpaceOrTabCharAtText(text, true);

if ($isCodeHighlightNode(node)) {
if (code.$isCodeHighlightNode(node)) {
const text = node.getTextContent();

@@ -514,3 +151,3 @@ const offset = findFirstNotSpaceOrTabCharAtText(text, false);

if ($isCodeHighlightNode(node)) {
if (code.$isCodeHighlightNode(node)) {
const text = node.getTextContent();

@@ -538,65 +175,2 @@ const offset = findFirstNotSpaceOrTabCharAtText(text, false);

function convertPreElement(domNode) {
return {
node: $createCodeNode()
};
}
function convertDivElement(domNode) {
// domNode is a <div> since we matched it by nodeName
const div = domNode;
return {
after: childLexicalNodes => {
const domParent = domNode.parentNode;
if (domParent != null && domNode !== domParent.lastChild) {
childLexicalNodes.push(lexical.$createLineBreakNode());
}
return childLexicalNodes;
},
node: isCodeElement(div) ? $createCodeNode() : null
};
}
function convertTableElement() {
return {
node: $createCodeNode()
};
}
function convertCodeNoop() {
return {
node: null
};
}
function convertTableCellElement(domNode) {
// domNode is a <td> since we matched it by nodeName
const cell = domNode;
return {
after: childLexicalNodes => {
if (cell.parentNode && cell.parentNode.nextSibling) {
// Append newline between code lines
childLexicalNodes.push(lexical.$createLineBreakNode());
}
return childLexicalNodes;
},
node: null
};
}
function isCodeElement(div) {
return div.style.fontFamily.match('monospace') !== null;
}
function isGitHubCodeCell(cell) {
return cell.classList.contains('js-file-line');
}
function isGitHubCodeTable(table) {
return table.classList.contains('js-file-line-container');
}
function textNodeTransform(node, editor) {

@@ -607,5 +181,5 @@ // Since CodeNode has flat children structure we only need to check

if ($isCodeNode(parentNode)) {
if (code.$isCodeNode(parentNode)) {
codeNodeTransform(parentNode, editor);
} else if ($isCodeHighlightNode(node)) {
} else if (code.$isCodeHighlightNode(node)) {
// When code block converted into paragraph or other element

@@ -648,3 +222,3 @@ // code highlight nodes converted back to normal text

// Using extra flag (`isHighlighting`) since both CodeNode and CodeHighlightNode
// trasnforms might be called at the same time (e.g. new CodeHighlight node inserted) and
// transforms might be called at the same time (e.g. new CodeHighlight node inserted) and
// in both cases we'll rerun whole reformatting over CodeNode, which is redundant.

@@ -664,3 +238,3 @@ // Especially when pasting code into CodeBlock.

if (node.getLanguage() === undefined) {
node.setLanguage(DEFAULT_CODE_LANGUAGE);
node.setLanguage(code.DEFAULT_CODE_LANGUAGE);
} // Using nested update call to pass `skipTransforms` since we don't want

@@ -673,4 +247,4 @@ // each individual codehighlight node to be transformed again as it's already

updateAndRetainSelection(node, () => {
const code = node.getTextContent();
const tokens = Prism.tokenize(code, Prism.languages[node.getLanguage() || ''] || Prism.languages[DEFAULT_CODE_LANGUAGE]);
const code$1 = node.getTextContent();
const tokens = Prism.tokenize(code$1, Prism.languages[node.getLanguage() || ''] || Prism.languages[code.DEFAULT_CODE_LANGUAGE]);
const highlightNodes = getHighlightNodes(tokens);

@@ -709,3 +283,3 @@ const diffRange = getDiffRange(node.getChildren(), highlightNodes);

if (text.length) {
nodes.push($createCodeHighlightNode(text));
nodes.push(code.$createCodeHighlightNode(text));
}

@@ -723,5 +297,5 @@

if (typeof content === 'string') {
nodes.push($createCodeHighlightNode(content, token.type));
nodes.push(code.$createCodeHighlightNode(content, token.type));
} else if (Array.isArray(content) && content.length === 1 && typeof content[0] === 'string') {
nodes.push($createCodeHighlightNode(content[0], token.type));
nodes.push(code.$createCodeHighlightNode(content[0], token.type));
} else if (Array.isArray(content)) {

@@ -828,3 +402,3 @@ nodes.push(...getHighlightNodes(content));

// returning false so that it's transformed into code highlight node
if ($isCodeHighlightNode(nodeA) && $isCodeHighlightNode(nodeB)) {
if (code.$isCodeHighlightNode(nodeA) && code.$isCodeHighlightNode(nodeB)) {
return nodeA.__text === nodeB.__text && nodeA.__highlightType === nodeB.__highlightType;

@@ -853,3 +427,3 @@ }

if (!$isCodeHighlightNode(node) && !lexical.$isLineBreakNode(node)) {
if (!code.$isCodeHighlightNode(node) && !lexical.$isLineBreakNode(node)) {
return false;

@@ -859,3 +433,3 @@ }

const startOfLine = getFirstCodeHighlightNodeOfLine(nodes[0]);
const startOfLine = code.getFirstCodeHighlightNodeOfLine(nodes[0]);

@@ -869,3 +443,3 @@ if (startOfLine != null) {

if (lexical.$isLineBreakNode(nodes[i - 1]) && $isCodeHighlightNode(node)) {
if (lexical.$isLineBreakNode(nodes[i - 1]) && code.$isCodeHighlightNode(node)) {
doIndent(node, type);

@@ -890,3 +464,3 @@ }

} else {
const indentNode = $createCodeHighlightNode('\t');
const indentNode = code.$createCodeHighlightNode('\t');
node.insertBefore(indentNode);

@@ -927,3 +501,3 @@ }

if (!$isCodeHighlightNode(anchorNode) || !$isCodeHighlightNode(focusNode)) {
if (!code.$isCodeHighlightNode(anchorNode) || !code.$isCodeHighlightNode(focusNode)) {
return false;

@@ -960,4 +534,4 @@ }

const start = getFirstCodeHighlightNodeOfLine(anchorNode);
const end = getLastCodeHighlightNodeOfLine(focusNode);
const start = code.getFirstCodeHighlightNodeOfLine(anchorNode);
const end = code.getLastCodeHighlightNodeOfLine(focusNode);

@@ -973,3 +547,3 @@ if (start == null || end == null) {

if (!$isCodeHighlightNode(node) && !lexical.$isLineBreakNode(node)) {
if (!code.$isCodeHighlightNode(node) && !lexical.$isLineBreakNode(node)) {
return false;

@@ -997,3 +571,3 @@ }

const maybeInsertionPoint = arrowIsUp ? getFirstCodeHighlightNodeOfLine(sibling) : getLastCodeHighlightNodeOfLine(sibling);
const maybeInsertionPoint = arrowIsUp ? code.getFirstCodeHighlightNodeOfLine(sibling) : code.getLastCodeHighlightNodeOfLine(sibling);
let insertionPoint = maybeInsertionPoint != null ? maybeInsertionPoint : sibling;

@@ -1034,3 +608,3 @@ linebreak.remove();

if (!$isCodeHighlightNode(anchorNode) || !$isCodeHighlightNode(focusNode)) {
if (!code.$isCodeHighlightNode(anchorNode) || !code.$isCodeHighlightNode(focusNode)) {
return false;

@@ -1064,7 +638,7 @@ }

function registerCodeHighlighting(editor) {
if (!editor.hasNodes([CodeNode, CodeHighlightNode])) {
if (!editor.hasNodes([code.CodeNode, code.CodeHighlightNode])) {
throw new Error('CodeHighlightPlugin: CodeNode or CodeHighlightNode not registered on editor');
}
return utils.mergeRegister(editor.registerMutationListener(CodeNode, mutations => {
return utils.mergeRegister(editor.registerMutationListener(code.CodeNode, mutations => {
editor.update(() => {

@@ -1081,5 +655,451 @@ for (const [key, type] of mutations) {

});
}), editor.registerNodeTransform(CodeNode, node => codeNodeTransform(node, editor)), editor.registerNodeTransform(lexical.TextNode, node => textNodeTransform(node, editor)), editor.registerNodeTransform(CodeHighlightNode, node => textNodeTransform(node, editor)), 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));
}), editor.registerNodeTransform(code.CodeNode, node => codeNodeTransform(node, editor)), editor.registerNodeTransform(lexical.TextNode, node => textNodeTransform(node, editor)), editor.registerNodeTransform(code.CodeHighlightNode, node => textNodeTransform(node, editor)), 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));
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
const DEFAULT_CODE_LANGUAGE = 'javascript';
const CODE_LANGUAGE_FRIENDLY_NAME_MAP = {
c: 'C',
clike: 'C-like',
css: 'CSS',
html: 'HTML',
js: 'JavaScript',
markdown: 'Markdown',
objc: 'Objective-C',
plain: 'Plain Text',
py: 'Python',
rust: 'Rust',
sql: 'SQL',
swift: 'Swift',
xml: 'XML'
};
const CODE_LANGUAGE_MAP = {
javascript: 'js',
md: 'markdown',
plaintext: 'plain',
python: 'py',
text: 'plain'
};
function normalizeCodeLang(lang) {
return CODE_LANGUAGE_MAP[lang] || lang;
}
function getLanguageFriendlyName(lang) {
const _lang = normalizeCodeLang(lang);
return CODE_LANGUAGE_FRIENDLY_NAME_MAP[_lang] || _lang;
}
const getDefaultCodeLanguage = () => DEFAULT_CODE_LANGUAGE;
const getCodeLanguages = () => Object.keys(Prism.languages).filter( // Prism has several language helpers mixed into languages object
// so filtering them out here to get langs list
language => typeof Prism.languages[language] !== 'function').sort();
class CodeHighlightNode extends lexical.TextNode {
constructor(text, highlightType, key) {
super(text, key);
this.__highlightType = highlightType;
}
static getType() {
return 'code-highlight';
}
static clone(node) {
return new CodeHighlightNode(node.__text, node.__highlightType || undefined, node.__key);
}
getHighlightType() {
const self = this.getLatest();
return self.__highlightType;
}
createDOM(config) {
const element = super.createDOM(config);
const className = getHighlightThemeClass(config.theme, this.__highlightType);
utils.addClassNamesToElement(element, className);
return element;
}
updateDOM(prevNode, dom, config) {
const update = super.updateDOM(prevNode, dom, config);
const prevClassName = getHighlightThemeClass(config.theme, prevNode.__highlightType);
const nextClassName = getHighlightThemeClass(config.theme, this.__highlightType);
if (prevClassName !== nextClassName) {
if (prevClassName) {
utils.removeClassNamesFromElement(dom, prevClassName);
}
if (nextClassName) {
utils.addClassNamesToElement(dom, nextClassName);
}
}
return update;
}
static importJSON(serializedNode) {
const node = $createCodeHighlightNode(serializedNode.text, serializedNode.highlightType);
node.setFormat(serializedNode.format);
node.setDetail(serializedNode.detail);
node.setMode(serializedNode.mode);
node.setStyle(serializedNode.style);
return node;
}
exportJSON() {
return { ...super.exportJSON(),
highlightType: this.getHighlightType(),
type: 'code-highlight',
version: 1
};
} // Prevent formatting (bold, underline, etc)
setFormat(format) {
return this;
}
}
function getHighlightThemeClass(theme, highlightType) {
return highlightType && theme && theme.codeHighlight && theme.codeHighlight[highlightType];
}
function $createCodeHighlightNode(text, highlightType) {
return new CodeHighlightNode(text, highlightType);
}
function $isCodeHighlightNode(node) {
return node instanceof CodeHighlightNode;
}
function getFirstCodeHighlightNodeOfLine(anchor) {
let currentNode = null;
const previousSiblings = anchor.getPreviousSiblings();
previousSiblings.push(anchor);
while (previousSiblings.length > 0) {
const node = previousSiblings.pop();
if ($isCodeHighlightNode(node)) {
currentNode = node;
}
if (lexical.$isLineBreakNode(node)) {
break;
}
}
return currentNode;
}
function getLastCodeHighlightNodeOfLine(anchor) {
let currentNode = null;
const nextSiblings = anchor.getNextSiblings();
nextSiblings.unshift(anchor);
while (nextSiblings.length > 0) {
const node = nextSiblings.shift();
if ($isCodeHighlightNode(node)) {
currentNode = node;
}
if (lexical.$isLineBreakNode(node)) {
break;
}
}
return currentNode;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
const mapToPrismLanguage = language => {
// eslint-disable-next-line no-prototype-builtins
return language != null && Prism.languages.hasOwnProperty(language) ? language : undefined;
};
const LANGUAGE_DATA_ATTRIBUTE = 'data-highlight-language';
class CodeNode extends lexical.ElementNode {
static getType() {
return 'code';
}
static clone(node) {
return new CodeNode(node.__language, node.__key);
}
constructor(language, key) {
super(key);
this.__language = mapToPrismLanguage(language);
} // View
createDOM(config) {
const element = document.createElement('code');
utils.addClassNamesToElement(element, config.theme.code);
element.setAttribute('spellcheck', 'false');
const language = this.getLanguage();
if (language) {
element.setAttribute(LANGUAGE_DATA_ATTRIBUTE, language);
}
return element;
}
updateDOM(prevNode, dom) {
const language = this.__language;
const prevLanguage = prevNode.__language;
if (language) {
if (language !== prevLanguage) {
dom.setAttribute(LANGUAGE_DATA_ATTRIBUTE, language);
}
} else if (prevLanguage) {
dom.removeAttribute(LANGUAGE_DATA_ATTRIBUTE);
}
return false;
}
static importDOM() {
return {
// Typically <pre> is used for code blocks, and <code> for inline code styles
// but if it's a multi line <code> we'll create a block. Pass through to
// inline format handled by TextNode otherwise
code: node => {
const isMultiLine = node.textContent != null && /\r?\n/.test(node.textContent);
return isMultiLine ? {
conversion: convertPreElement,
priority: 1
} : null;
},
div: node => ({
conversion: convertDivElement,
priority: 1
}),
pre: node => ({
conversion: convertPreElement,
priority: 0
}),
table: node => {
const table = node; // domNode is a <table> since we matched it by nodeName
if (isGitHubCodeTable(table)) {
return {
conversion: convertTableElement,
priority: 4
};
}
return null;
},
td: node => {
// element is a <td> since we matched it by nodeName
const td = node;
const table = td.closest('table');
if (isGitHubCodeCell(td)) {
return {
conversion: convertTableCellElement,
priority: 4
};
}
if (table && isGitHubCodeTable(table)) {
// Return a no-op if it's a table cell in a code table, but not a code line.
// Otherwise it'll fall back to the T
return {
conversion: convertCodeNoop,
priority: 4
};
}
return null;
},
tr: node => {
// element is a <tr> since we matched it by nodeName
const tr = node;
const table = tr.closest('table');
if (table && isGitHubCodeTable(table)) {
return {
conversion: convertCodeNoop,
priority: 4
};
}
return null;
}
};
}
static importJSON(serializedNode) {
const node = $createCodeNode(serializedNode.language);
node.setFormat(serializedNode.format);
node.setIndent(serializedNode.indent);
node.setDirection(serializedNode.direction);
return node;
}
exportJSON() {
return { ...super.exportJSON(),
language: this.getLanguage(),
type: 'code',
version: 1
};
} // Mutation
insertNewAfter(selection) {
const children = this.getChildren();
const childrenLength = children.length;
if (childrenLength >= 2 && children[childrenLength - 1].getTextContent() === '\n' && children[childrenLength - 2].getTextContent() === '\n' && selection.isCollapsed() && selection.anchor.key === this.__key && selection.anchor.offset === childrenLength) {
children[childrenLength - 1].remove();
children[childrenLength - 2].remove();
const newElement = lexical.$createParagraphNode();
this.insertAfter(newElement);
return newElement;
} // If the selection is within the codeblock, find all leading tabs and
// spaces of the current line. Create a new line that has all those
// tabs and spaces, such that leading indentation is preserved.
const anchor = selection.anchor.getNode();
const firstNode = code.getFirstCodeHighlightNodeOfLine(anchor);
if (firstNode != null) {
let leadingWhitespace = 0;
const firstNodeText = firstNode.getTextContent();
while (leadingWhitespace < firstNodeText.length && /[\t ]/.test(firstNodeText[leadingWhitespace])) {
leadingWhitespace += 1;
}
if (leadingWhitespace > 0) {
const whitespace = firstNodeText.substring(0, leadingWhitespace);
const indentedChild = code.$createCodeHighlightNode(whitespace);
anchor.insertAfter(indentedChild);
selection.insertNodes([lexical.$createLineBreakNode()]);
indentedChild.select();
return indentedChild;
}
}
return null;
}
canInsertTab() {
const selection = lexical.$getSelection();
if (!lexical.$isRangeSelection(selection) || !selection.isCollapsed()) {
return false;
}
return true;
}
canIndent() {
return false;
}
collapseAtStart() {
const paragraph = lexical.$createParagraphNode();
const children = this.getChildren();
children.forEach(child => paragraph.append(child));
this.replace(paragraph);
return true;
}
setLanguage(language) {
const writable = this.getWritable();
writable.__language = mapToPrismLanguage(language);
}
getLanguage() {
return this.getLatest().__language;
}
}
function $createCodeNode(language) {
return new CodeNode(language);
}
function $isCodeNode(node) {
return node instanceof CodeNode;
}
function convertPreElement(domNode) {
return {
node: $createCodeNode()
};
}
function convertDivElement(domNode) {
// domNode is a <div> since we matched it by nodeName
const div = domNode;
return {
after: childLexicalNodes => {
const domParent = domNode.parentNode;
if (domParent != null && domNode !== domParent.lastChild) {
childLexicalNodes.push(lexical.$createLineBreakNode());
}
return childLexicalNodes;
},
node: isCodeElement(div) ? $createCodeNode() : null
};
}
function convertTableElement() {
return {
node: $createCodeNode()
};
}
function convertCodeNoop() {
return {
node: null
};
}
function convertTableCellElement(domNode) {
// domNode is a <td> since we matched it by nodeName
const cell = domNode;
return {
after: childLexicalNodes => {
if (cell.parentNode && cell.parentNode.nextSibling) {
// Append newline between code lines
childLexicalNodes.push(lexical.$createLineBreakNode());
}
return childLexicalNodes;
},
node: null
};
}
function isCodeElement(div) {
return div.style.fontFamily.match('monospace') !== null;
}
function isGitHubCodeCell(cell) {
return cell.classList.contains('js-file-line');
}
function isGitHubCodeTable(table) {
return table.classList.contains('js-file-line-container');
}
exports.$createCodeHighlightNode = $createCodeHighlightNode;

@@ -1093,2 +1113,3 @@ exports.$createCodeNode = $createCodeNode;

exports.CodeNode = CodeNode;
exports.DEFAULT_CODE_LANGUAGE = DEFAULT_CODE_LANGUAGE;
exports.getCodeLanguages = getCodeLanguages;

@@ -1101,2 +1122,3 @@ exports.getDefaultCodeLanguage = getDefaultCodeLanguage;

exports.getStartOfCodeInLine = getStartOfCodeInLine;
exports.normalizeCodeLang = normalizeCodeLang;
exports.registerCodeHighlighting = registerCodeHighlighting;

@@ -8,27 +8,30 @@ /**

'use strict';var e=require("prismjs");require("prismjs/components/prism-clike");require("prismjs/components/prism-javascript");require("prismjs/components/prism-markup");require("prismjs/components/prism-markdown");require("prismjs/components/prism-c");require("prismjs/components/prism-css");require("prismjs/components/prism-objectivec");require("prismjs/components/prism-sql");require("prismjs/components/prism-python");require("prismjs/components/prism-rust");require("prismjs/components/prism-swift");
var m=require("@lexical/utils"),r=require("lexical");let t={c:"C",clike:"C-like",css:"CSS",html:"HTML",js:"JavaScript",markdown:"Markdown",objc:"Objective-C",plain:"Plain Text",py:"Python",rust:"Rust",sql:"SQL",swift:"Swift",xml:"XML"},u={javascript:"js",md:"markdown",plaintext:"plain",python:"py",text:"plain"},v=a=>null!=a&&e.languages.hasOwnProperty(a)?a:void 0;
class y extends r.TextNode{constructor(a,b,c){super(a,c);this.__highlightType=b}static getType(){return"code-highlight"}static clone(a){return new y(a.__text,a.__highlightType||void 0,a.__key)}getHighlightType(){return this.getLatest().__highlightType}createDOM(a){let b=super.createDOM(a);a=z(a.theme,this.__highlightType);m.addClassNamesToElement(b,a);return b}updateDOM(a,b,c){let d=super.updateDOM(a,b,c);a=z(c.theme,a.__highlightType);c=z(c.theme,this.__highlightType);a!==c&&(a&&m.removeClassNamesFromElement(b,
a),c&&m.addClassNamesToElement(b,c));return d}static importJSON(a){let b=A(a.text,a.highlightType);b.setFormat(a.format);b.setDetail(a.detail);b.setMode(a.mode);b.setStyle(a.style);return b}exportJSON(){return{...super.exportJSON(),highlightType:this.getHighlightType(),type:"code-highlight",version:1}}setFormat(){return this}}function z(a,b){return b&&a&&a.codeHighlight&&a.codeHighlight[b]}function A(a,b){return new y(a,b)}function C(a){return a instanceof y}
class D extends r.ElementNode{static getType(){return"code"}static clone(a){return new D(a.__language,a.__key)}constructor(a,b){super(b);this.__language=v(a)}createDOM(a){let b=document.createElement("code");m.addClassNamesToElement(b,a.theme.code);b.setAttribute("spellcheck","false");(a=this.getLanguage())&&b.setAttribute("data-highlight-language",a);return b}updateDOM(a,b){let c=this.__language;a=a.__language;c?c!==a&&b.setAttribute("data-highlight-language",c):a&&b.removeAttribute("data-highlight-language");
return!1}static importDOM(){return{code:a=>null!=a.textContent&&/\r?\n/.test(a.textContent)?{conversion:E,priority:1}:null,div:()=>({conversion:F,priority:1}),pre:()=>({conversion:E,priority:0}),table:a=>G(a)?{conversion:H,priority:4}:null,td:a=>{let b=a.closest("table");return a.classList.contains("js-file-line")?{conversion:aa,priority:4}:b&&G(b)?{conversion:I,priority:4}:null},tr:a=>(a=a.closest("table"))&&G(a)?{conversion:I,priority:4}:null}}static importJSON(a){let b=J(a.language);b.setFormat(a.format);
b.setIndent(a.indent);b.setDirection(a.direction);return b}exportJSON(){return{...super.exportJSON(),language:this.getLanguage(),type:"code",version:1}}insertNewAfter(a){var b=this.getChildren(),c=b.length;if(2<=c&&"\n"===b[c-1].getTextContent()&&"\n"===b[c-2].getTextContent()&&a.isCollapsed()&&a.anchor.key===this.__key&&a.anchor.offset===c)return b[c-1].remove(),b[c-2].remove(),a=r.$createParagraphNode(),this.insertAfter(a),a;b=a.anchor.getNode();var d=K(b);if(null!=d){c=0;for(d=d.getTextContent();c<
d.length&&/[\t ]/.test(d[c]);)c+=1;if(0<c)return c=d.substring(0,c),c=A(c),b.insertAfter(c),a.insertNodes([r.$createLineBreakNode()]),c.select(),c}return null}canInsertTab(){let a=r.$getSelection();return r.$isRangeSelection(a)&&a.isCollapsed()?!0:!1}canIndent(){return!1}collapseAtStart(){let a=r.$createParagraphNode();this.getChildren().forEach(b=>a.append(b));this.replace(a);return!0}setLanguage(a){this.getWritable().__language=v(a)}getLanguage(){return this.getLatest().__language}}
function J(a){return new D(a)}function L(a){return a instanceof D}function K(a){let b=null,c=a.getPreviousSiblings();for(c.push(a);0<c.length&&(a=c.pop(),C(a)&&(b=a),!r.$isLineBreakNode(a)););return b}function M(a){let b=null,c=a.getNextSiblings();for(c.unshift(a);0<c.length&&(a=c.shift(),C(a)&&(b=a),!r.$isLineBreakNode(a)););return b}
function N(a,b){var c=a.length;let d=-1;if(b)for(b=0;b<c;b++){let f=a[b];if(" "!==f&&"\t"!==f){d=b;break}}else for(--c;-1<c;c--)if(b=a[c]," "!==b&&"\t"!==b){d=c;break}return d}
function O(a){let b=null,c=-1;var d=a.getPreviousSiblings();for(d.push(a);0<d.length;){var f=d.pop();if(C(f)){var g=f.getTextContent();g=N(g,!0);-1!==g&&(b=f,c=g)}if(r.$isLineBreakNode(f))break}if(null===b)for(a=a.getNextSiblings();0<a.length;){d=a.shift();if(C(d)&&(f=d.getTextContent(),f=N(f,!0),-1!==f)){b=d;c=f;break}if(r.$isLineBreakNode(d))break}return{node:b,offset:c}}
function P(a){let b=null,c=-1;var d=a.getNextSiblings();for(d.unshift(a);0<d.length;){var f=d.shift();if(C(f)){var g=f.getTextContent();g=N(g,!1);-1!==g&&(b=f,c=g+1)}if(r.$isLineBreakNode(f))break}if(null===b)for(a=a.getPreviousSiblings();0<a.length;){d=a.pop();if(C(d)&&(f=d.getTextContent(),f=N(f,!1),-1!==f)){b=d;c=f+1;break}if(r.$isLineBreakNode(d))break}return{node:b,offset:c}}function E(){return{node:J()}}
function F(a){return{after:b=>{let c=a.parentNode;null!=c&&a!==c.lastChild&&b.push(r.$createLineBreakNode());return b},node:null!==a.style.fontFamily.match("monospace")?J():null}}function H(){return{node:J()}}function I(){return{node:null}}function aa(a){return{after:b=>{a.parentNode&&a.parentNode.nextSibling&&b.push(r.$createLineBreakNode());return b},node:null}}function G(a){return a.classList.contains("js-file-line-container")}
function Q(a,b){let c=a.getParent();L(c)?R(c,b):C(a)&&a.replace(r.$createTextNode(a.__text))}let S=!1;
function R(a,b){S||(S=!0,void 0===a.getLanguage()&&a.setLanguage("javascript"),b.update(()=>{ba(a,()=>{var c=a.getTextContent();c=e.tokenize(c,e.languages[a.getLanguage()||""]||e.languages.javascript);c=T(c);var d=a.getChildren();let f=0;for(;f<d.length&&U(d[f],c[f]);)f++;var g=d.length;let l=c.length,h=Math.min(g,l)-f,k=0;for(;k<h;)if(k++,!U(d[g-k],c[l-k])){k--;break}d=f;g-=k;c=c.slice(f,l-k);let {from:n,to:p,nodesForReplacement:w}={from:d,nodesForReplacement:c,to:g};return n!==p||w.length?(a.splice(n,
p-n,w),!0):!1})},{onUpdate:()=>{S=!1},skipTransforms:!0}))}function T(a){let b=[];a.forEach(c=>{if("string"===typeof c){c=c.split("\n");for(var d=0;d<c.length;d++){let f=c[d];f.length&&b.push(A(f));d<c.length-1&&b.push(r.$createLineBreakNode())}}else({content:d}=c),"string"===typeof d?b.push(A(d,c.type)):Array.isArray(d)&&1===d.length&&"string"===typeof d[0]?b.push(A(d[0],c.type)):Array.isArray(d)&&b.push(...T(d))});return b}
function ba(a,b){var c=r.$getSelection();if(r.$isRangeSelection(c)&&c.anchor){c=c.anchor;var d=c.offset,f="element"===c.type&&r.$isLineBreakNode(a.getChildAtIndex(c.offset-1)),g=0;if(!f){let l=c.getNode();g=d+l.getPreviousSiblings().reduce((h,k)=>h+(r.$isLineBreakNode(k)?0:k.getTextContentSize()),0)}b()&&(f?c.getNode().select(d,d):a.getChildren().some(l=>{if(r.$isTextNode(l)){let h=l.getTextContentSize();if(h>=g)return l.select(g,g),!0;g-=h}return!1}))}}
function U(a,b){return C(a)&&C(b)?a.__text===b.__text&&a.__highlightType===b.__highlightType:r.$isLineBreakNode(a)&&r.$isLineBreakNode(b)?!0:!1}function V(a){var b=r.$getSelection();if(!r.$isRangeSelection(b)||b.isCollapsed())return!1;b=b.getNodes();for(var c=0;c<b.length;c++){var d=b[c];if(!C(d)&&!r.$isLineBreakNode(d))return!1}c=K(b[0]);null!=c&&X(c,a);for(c=1;c<b.length;c++)d=b[c],r.$isLineBreakNode(b[c-1])&&C(d)&&X(d,a);return!0}
function X(a,b){let c=a.getTextContent();b===r.INDENT_CONTENT_COMMAND?0<c.length&&/\s/.test(c[0])?a.setTextContent("\t"+c):(b=A("\t"),a.insertBefore(b)):0===c.indexOf("\t")&&(1===c.length?a.remove():a.setTextContent(c.substring(1)))}
function Y(a,b){let c=r.$getSelection();if(!r.$isRangeSelection(c))return!1;let {anchor:d,focus:f}=c,g=d.offset,l=f.offset,h=d.getNode(),k=f.getNode();var n=a===r.KEY_ARROW_UP_COMMAND;if(!C(h)||!C(k))return!1;if(!b.altKey){if(c.isCollapsed())if(a=h.getParentOrThrow(),n&&0===g&&null===h.getPreviousSibling()){if(null===a.getPreviousSibling())return a.selectPrevious(),b.preventDefault(),!0}else if(!n&&g===h.getTextContentSize()&&null===h.getNextSibling()&&null===a.getNextSibling())return a.selectNext(),
b.preventDefault(),!0;return!1}var p=K(h);let w=M(k);if(null==p||null==w)return!1;let B=p.getNodesBetween(w);for(let q=0;q<B.length;q++){let W=B[q];if(!C(W)&&!r.$isLineBreakNode(W))return!1}b.preventDefault();b.stopPropagation();b=n?p.getPreviousSibling():w.getNextSibling();if(!r.$isLineBreakNode(b))return!0;p=n?b.getPreviousSibling():b.getNextSibling();if(null==p)return!0;n=n?K(p):M(p);let x=null!=n?n:p;b.remove();B.forEach(q=>q.remove());a===r.KEY_ARROW_UP_COMMAND?(B.forEach(q=>x.insertBefore(q)),
x.insertBefore(b)):(x.insertAfter(b),x=b,B.forEach(q=>{x.insertAfter(q);x=q}));c.setTextNodeRange(h,g,k,l);return!0}function Z(a,b){let c=r.$getSelection();if(!r.$isRangeSelection(c))return!1;let {anchor:d,focus:f}=c,g=d.getNode(),l=f.getNode();a=a===r.MOVE_TO_START;if(!C(g)||!C(l))return!1;let h,k;a?{node:h,offset:k}=O(l):{node:h,offset:k}=P(l);null!==h&&-1!==k&&c.setTextNodeRange(h,k,h,k);b.preventDefault();b.stopPropagation();return!0}exports.$createCodeHighlightNode=A;
exports.$createCodeNode=J;exports.$isCodeHighlightNode=C;exports.$isCodeNode=L;exports.CODE_LANGUAGE_FRIENDLY_NAME_MAP=t;exports.CODE_LANGUAGE_MAP=u;exports.CodeHighlightNode=y;exports.CodeNode=D;exports.getCodeLanguages=()=>Object.keys(e.languages).filter(a=>"function"!==typeof e.languages[a]).sort();exports.getDefaultCodeLanguage=()=>"javascript";exports.getEndOfCodeInLine=P;exports.getFirstCodeHighlightNodeOfLine=K;exports.getLanguageFriendlyName=function(a){a=u[a]||a;return t[a]||a};
exports.getLastCodeHighlightNodeOfLine=M;exports.getStartOfCodeInLine=O;
exports.registerCodeHighlighting=function(a){if(!a.hasNodes([D,y]))throw Error("CodeHighlightPlugin: CodeNode or CodeHighlightNode not registered on editor");return m.mergeRegister(a.registerMutationListener(D,b=>{a.update(()=>{for(let [f,g]of b)if("destroyed"!==g){var c=r.$getNodeByKey(f);if(null!==c)a:{var d=c;c=a.getElementByKey(d.getKey());if(null===c)break a;d=d.getChildren();let l=d.length;if(l===c.__cachedChildrenLength)break a;c.__cachedChildrenLength=l;let h="1",k=1;for(let n=0;n<l;n++)r.$isLineBreakNode(d[n])&&
(h+="\n"+ ++k);c.setAttribute("data-gutter",h)}}})}),a.registerNodeTransform(D,b=>R(b,a)),a.registerNodeTransform(r.TextNode,b=>Q(b,a)),a.registerNodeTransform(y,b=>Q(b,a)),a.registerCommand(r.INDENT_CONTENT_COMMAND,()=>V(r.INDENT_CONTENT_COMMAND),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.OUTDENT_CONTENT_COMMAND,()=>V(r.OUTDENT_CONTENT_COMMAND),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.KEY_ARROW_UP_COMMAND,b=>Y(r.KEY_ARROW_UP_COMMAND,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.KEY_ARROW_DOWN_COMMAND,
b=>Y(r.KEY_ARROW_DOWN_COMMAND,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.MOVE_TO_END,b=>Z(r.MOVE_TO_END,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.MOVE_TO_START,b=>Z(r.MOVE_TO_START,b),r.COMMAND_PRIORITY_LOW))}
var g=require("@lexical/utils"),r=require("lexical"),v=require("@lexical/code");function x(a,b){var c=a.length;let d=-1;if(b)for(b=0;b<c;b++){let f=a[b];if(" "!==f&&"\t"!==f){d=b;break}}else for(--c;-1<c;c--)if(b=a[c]," "!==b&&"\t"!==b){d=c;break}return d}
function y(a){let b=null,c=-1;var d=a.getPreviousSiblings();for(d.push(a);0<d.length;){var f=d.pop();if(v.$isCodeHighlightNode(f)){var h=f.getTextContent();h=x(h,!0);-1!==h&&(b=f,c=h)}if(r.$isLineBreakNode(f))break}if(null===b)for(a=a.getNextSiblings();0<a.length;){d=a.shift();if(v.$isCodeHighlightNode(d)&&(f=d.getTextContent(),f=x(f,!0),-1!==f)){b=d;c=f;break}if(r.$isLineBreakNode(d))break}return{node:b,offset:c}}
function z(a){let b=null,c=-1;var d=a.getNextSiblings();for(d.unshift(a);0<d.length;){var f=d.shift();if(v.$isCodeHighlightNode(f)){var h=f.getTextContent();h=x(h,!1);-1!==h&&(b=f,c=h+1)}if(r.$isLineBreakNode(f))break}if(null===b)for(a=a.getPreviousSiblings();0<a.length;){d=a.pop();if(v.$isCodeHighlightNode(d)&&(f=d.getTextContent(),f=x(f,!1),-1!==f)){b=d;c=f+1;break}if(r.$isLineBreakNode(d))break}return{node:b,offset:c}}
function A(a,b){let c=a.getParent();v.$isCodeNode(c)?B(c,b):v.$isCodeHighlightNode(a)&&a.replace(r.$createTextNode(a.__text))}let C=!1;
function B(a,b){C||(C=!0,void 0===a.getLanguage()&&a.setLanguage(v.DEFAULT_CODE_LANGUAGE),b.update(()=>{D(a,()=>{var c=a.getTextContent();c=e.tokenize(c,e.languages[a.getLanguage()||""]||e.languages[v.DEFAULT_CODE_LANGUAGE]);c=E(c);var d=a.getChildren();let f=0;for(;f<d.length&&F(d[f],c[f]);)f++;var h=d.length;let m=c.length,k=Math.min(h,m)-f,l=0;for(;l<k;)if(l++,!F(d[h-l],c[m-l])){l--;break}d=f;h-=l;c=c.slice(f,m-l);let {from:n,to:p,nodesForReplacement:t}={from:d,nodesForReplacement:c,to:h};return n!==
p||t.length?(a.splice(n,p-n,t),!0):!1})},{onUpdate:()=>{C=!1},skipTransforms:!0}))}
function E(a){let b=[];a.forEach(c=>{if("string"===typeof c){c=c.split("\n");for(var d=0;d<c.length;d++){let f=c[d];f.length&&b.push(v.$createCodeHighlightNode(f));d<c.length-1&&b.push(r.$createLineBreakNode())}}else({content:d}=c),"string"===typeof d?b.push(v.$createCodeHighlightNode(d,c.type)):Array.isArray(d)&&1===d.length&&"string"===typeof d[0]?b.push(v.$createCodeHighlightNode(d[0],c.type)):Array.isArray(d)&&b.push(...E(d))});return b}
function D(a,b){var c=r.$getSelection();if(r.$isRangeSelection(c)&&c.anchor){c=c.anchor;var d=c.offset,f="element"===c.type&&r.$isLineBreakNode(a.getChildAtIndex(c.offset-1)),h=0;if(!f){let m=c.getNode();h=d+m.getPreviousSiblings().reduce((k,l)=>k+(r.$isLineBreakNode(l)?0:l.getTextContentSize()),0)}b()&&(f?c.getNode().select(d,d):a.getChildren().some(m=>{if(r.$isTextNode(m)){let k=m.getTextContentSize();if(k>=h)return m.select(h,h),!0;h-=k}return!1}))}}
function F(a,b){return v.$isCodeHighlightNode(a)&&v.$isCodeHighlightNode(b)?a.__text===b.__text&&a.__highlightType===b.__highlightType:r.$isLineBreakNode(a)&&r.$isLineBreakNode(b)?!0:!1}
function G(a){var b=r.$getSelection();if(!r.$isRangeSelection(b)||b.isCollapsed())return!1;b=b.getNodes();for(var c=0;c<b.length;c++){var d=b[c];if(!v.$isCodeHighlightNode(d)&&!r.$isLineBreakNode(d))return!1}c=v.getFirstCodeHighlightNodeOfLine(b[0]);null!=c&&H(c,a);for(c=1;c<b.length;c++)d=b[c],r.$isLineBreakNode(b[c-1])&&v.$isCodeHighlightNode(d)&&H(d,a);return!0}
function H(a,b){let c=a.getTextContent();b===r.INDENT_CONTENT_COMMAND?0<c.length&&/\s/.test(c[0])?a.setTextContent("\t"+c):(b=v.$createCodeHighlightNode("\t"),a.insertBefore(b)):0===c.indexOf("\t")&&(1===c.length?a.remove():a.setTextContent(c.substring(1)))}
function I(a,b){let c=r.$getSelection();if(!r.$isRangeSelection(c))return!1;let {anchor:d,focus:f}=c,h=d.offset,m=f.offset,k=d.getNode(),l=f.getNode();var n=a===r.KEY_ARROW_UP_COMMAND;if(!v.$isCodeHighlightNode(k)||!v.$isCodeHighlightNode(l))return!1;if(!b.altKey){if(c.isCollapsed())if(a=k.getParentOrThrow(),n&&0===h&&null===k.getPreviousSibling()){if(null===a.getPreviousSibling())return a.selectPrevious(),b.preventDefault(),!0}else if(!n&&h===k.getTextContentSize()&&null===k.getNextSibling()&&null===
a.getNextSibling())return a.selectNext(),b.preventDefault(),!0;return!1}var p=v.getFirstCodeHighlightNodeOfLine(k);let t=v.getLastCodeHighlightNodeOfLine(l);if(null==p||null==t)return!1;let w=p.getNodesBetween(t);for(let q=0;q<w.length;q++){let O=w[q];if(!v.$isCodeHighlightNode(O)&&!r.$isLineBreakNode(O))return!1}b.preventDefault();b.stopPropagation();b=n?p.getPreviousSibling():t.getNextSibling();if(!r.$isLineBreakNode(b))return!0;p=n?b.getPreviousSibling():b.getNextSibling();if(null==p)return!0;
n=n?v.getFirstCodeHighlightNodeOfLine(p):v.getLastCodeHighlightNodeOfLine(p);let u=null!=n?n:p;b.remove();w.forEach(q=>q.remove());a===r.KEY_ARROW_UP_COMMAND?(w.forEach(q=>u.insertBefore(q)),u.insertBefore(b)):(u.insertAfter(b),u=b,w.forEach(q=>{u.insertAfter(q);u=q}));c.setTextNodeRange(k,h,l,m);return!0}
function J(a,b){let c=r.$getSelection();if(!r.$isRangeSelection(c))return!1;let {anchor:d,focus:f}=c,h=d.getNode(),m=f.getNode();a=a===r.MOVE_TO_START;if(!v.$isCodeHighlightNode(h)||!v.$isCodeHighlightNode(m))return!1;let k,l;a?{node:k,offset:l}=y(m):{node:k,offset:l}=z(m);null!==k&&-1!==l&&c.setTextNodeRange(k,l,k,l);b.preventDefault();b.stopPropagation();return!0}
let K={c:"C",clike:"C-like",css:"CSS",html:"HTML",js:"JavaScript",markdown:"Markdown",objc:"Objective-C",plain:"Plain Text",py:"Python",rust:"Rust",sql:"SQL",swift:"Swift",xml:"XML"},L={javascript:"js",md:"markdown",plaintext:"plain",python:"py",text:"plain"};function M(a){return L[a]||a}
class N extends r.TextNode{constructor(a,b,c){super(a,c);this.__highlightType=b}static getType(){return"code-highlight"}static clone(a){return new N(a.__text,a.__highlightType||void 0,a.__key)}getHighlightType(){return this.getLatest().__highlightType}createDOM(a){let b=super.createDOM(a);a=P(a.theme,this.__highlightType);g.addClassNamesToElement(b,a);return b}updateDOM(a,b,c){let d=super.updateDOM(a,b,c);a=P(c.theme,a.__highlightType);c=P(c.theme,this.__highlightType);a!==c&&(a&&g.removeClassNamesFromElement(b,
a),c&&g.addClassNamesToElement(b,c));return d}static importJSON(a){let b=Q(a.text,a.highlightType);b.setFormat(a.format);b.setDetail(a.detail);b.setMode(a.mode);b.setStyle(a.style);return b}exportJSON(){return{...super.exportJSON(),highlightType:this.getHighlightType(),type:"code-highlight",version:1}}setFormat(){return this}}function P(a,b){return b&&a&&a.codeHighlight&&a.codeHighlight[b]}function Q(a,b){return new N(a,b)}function R(a){return a instanceof N}
let S=a=>null!=a&&e.languages.hasOwnProperty(a)?a:void 0;
class T extends r.ElementNode{static getType(){return"code"}static clone(a){return new T(a.__language,a.__key)}constructor(a,b){super(b);this.__language=S(a)}createDOM(a){let b=document.createElement("code");g.addClassNamesToElement(b,a.theme.code);b.setAttribute("spellcheck","false");(a=this.getLanguage())&&b.setAttribute("data-highlight-language",a);return b}updateDOM(a,b){let c=this.__language;a=a.__language;c?c!==a&&b.setAttribute("data-highlight-language",c):a&&b.removeAttribute("data-highlight-language");
return!1}static importDOM(){return{code:a=>null!=a.textContent&&/\r?\n/.test(a.textContent)?{conversion:U,priority:1}:null,div:()=>({conversion:V,priority:1}),pre:()=>({conversion:U,priority:0}),table:a=>W(a)?{conversion:X,priority:4}:null,td:a=>{let b=a.closest("table");return a.classList.contains("js-file-line")?{conversion:aa,priority:4}:b&&W(b)?{conversion:Y,priority:4}:null},tr:a=>(a=a.closest("table"))&&W(a)?{conversion:Y,priority:4}:null}}static importJSON(a){let b=Z(a.language);b.setFormat(a.format);
b.setIndent(a.indent);b.setDirection(a.direction);return b}exportJSON(){return{...super.exportJSON(),language:this.getLanguage(),type:"code",version:1}}insertNewAfter(a){var b=this.getChildren(),c=b.length;if(2<=c&&"\n"===b[c-1].getTextContent()&&"\n"===b[c-2].getTextContent()&&a.isCollapsed()&&a.anchor.key===this.__key&&a.anchor.offset===c)return b[c-1].remove(),b[c-2].remove(),a=r.$createParagraphNode(),this.insertAfter(a),a;b=a.anchor.getNode();var d=v.getFirstCodeHighlightNodeOfLine(b);if(null!=
d){c=0;for(d=d.getTextContent();c<d.length&&/[\t ]/.test(d[c]);)c+=1;if(0<c)return c=d.substring(0,c),c=v.$createCodeHighlightNode(c),b.insertAfter(c),a.insertNodes([r.$createLineBreakNode()]),c.select(),c}return null}canInsertTab(){let a=r.$getSelection();return r.$isRangeSelection(a)&&a.isCollapsed()?!0:!1}canIndent(){return!1}collapseAtStart(){let a=r.$createParagraphNode();this.getChildren().forEach(b=>a.append(b));this.replace(a);return!0}setLanguage(a){this.getWritable().__language=S(a)}getLanguage(){return this.getLatest().__language}}
function Z(a){return new T(a)}function U(){return{node:Z()}}function V(a){return{after:b=>{let c=a.parentNode;null!=c&&a!==c.lastChild&&b.push(r.$createLineBreakNode());return b},node:null!==a.style.fontFamily.match("monospace")?Z():null}}function X(){return{node:Z()}}function Y(){return{node:null}}function aa(a){return{after:b=>{a.parentNode&&a.parentNode.nextSibling&&b.push(r.$createLineBreakNode());return b},node:null}}function W(a){return a.classList.contains("js-file-line-container")}
exports.$createCodeHighlightNode=Q;exports.$createCodeNode=Z;exports.$isCodeHighlightNode=R;exports.$isCodeNode=function(a){return a instanceof T};exports.CODE_LANGUAGE_FRIENDLY_NAME_MAP=K;exports.CODE_LANGUAGE_MAP=L;exports.CodeHighlightNode=N;exports.CodeNode=T;exports.DEFAULT_CODE_LANGUAGE="javascript";exports.getCodeLanguages=()=>Object.keys(e.languages).filter(a=>"function"!==typeof e.languages[a]).sort();exports.getDefaultCodeLanguage=()=>"javascript";exports.getEndOfCodeInLine=z;
exports.getFirstCodeHighlightNodeOfLine=function(a){let b=null,c=a.getPreviousSiblings();for(c.push(a);0<c.length&&(a=c.pop(),R(a)&&(b=a),!r.$isLineBreakNode(a)););return b};exports.getLanguageFriendlyName=function(a){a=M(a);return K[a]||a};exports.getLastCodeHighlightNodeOfLine=function(a){let b=null,c=a.getNextSiblings();for(c.unshift(a);0<c.length&&(a=c.shift(),R(a)&&(b=a),!r.$isLineBreakNode(a)););return b};exports.getStartOfCodeInLine=y;exports.normalizeCodeLang=M;
exports.registerCodeHighlighting=function(a){if(!a.hasNodes([v.CodeNode,v.CodeHighlightNode]))throw Error("CodeHighlightPlugin: CodeNode or CodeHighlightNode not registered on editor");return g.mergeRegister(a.registerMutationListener(v.CodeNode,b=>{a.update(()=>{for(let [f,h]of b)if("destroyed"!==h){var c=r.$getNodeByKey(f);if(null!==c)a:{var d=c;c=a.getElementByKey(d.getKey());if(null===c)break a;d=d.getChildren();let m=d.length;if(m===c.__cachedChildrenLength)break a;c.__cachedChildrenLength=m;
let k="1",l=1;for(let n=0;n<m;n++)r.$isLineBreakNode(d[n])&&(k+="\n"+ ++l);c.setAttribute("data-gutter",k)}}})}),a.registerNodeTransform(v.CodeNode,b=>B(b,a)),a.registerNodeTransform(r.TextNode,b=>A(b,a)),a.registerNodeTransform(v.CodeHighlightNode,b=>A(b,a)),a.registerCommand(r.INDENT_CONTENT_COMMAND,()=>G(r.INDENT_CONTENT_COMMAND),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.OUTDENT_CONTENT_COMMAND,()=>G(r.OUTDENT_CONTENT_COMMAND),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.KEY_ARROW_UP_COMMAND,
b=>I(r.KEY_ARROW_UP_COMMAND,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.KEY_ARROW_DOWN_COMMAND,b=>I(r.KEY_ARROW_DOWN_COMMAND,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.MOVE_TO_END,b=>J(r.MOVE_TO_END,b),r.COMMAND_PRIORITY_LOW),a.registerCommand(r.MOVE_TO_START,b=>J(r.MOVE_TO_START,b),r.COMMAND_PRIORITY_LOW))}

@@ -11,9 +11,9 @@ {

"license": "MIT",
"version": "0.3.8",
"version": "0.3.9",
"main": "LexicalCode.js",
"peerDependencies": {
"lexical": "0.3.8"
"lexical": "0.3.9"
},
"dependencies": {
"@lexical/utils": "0.3.8",
"@lexical/utils": "0.3.9",
"prismjs": "^1.27.0"

@@ -20,0 +20,0 @@ },

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc