@lobehub/editor
Version:
A powerful and extensible rich text editor built on Meta's Lexical framework, providing a modern editing experience with React integration.
77 lines • 3.17 kB
JavaScript
import { $findMatchingParent, mergeRegister } from '@lexical/utils';
import { $getNodeByKey, $getSelection, $insertNodes, $isRangeSelection, $setSelection, COMMAND_PRIORITY_EDITOR, createCommand } from 'lexical';
import { UPDATE_CODEBLOCK_LANG } from "../../codeblock";
import { $createCodeMirrorNode, $isCodeMirrorNode } from "../node/CodeMirrorNode";
export var INSERT_CODEMIRROR_COMMAND = createCommand('INSERT_CODEMIRROR_COMMAND');
export var SELECT_BEFORE_CODEMIRROR_COMMAND = createCommand('SELECT_BEFORE_CODEMIRROR_COMMAND');
export var SELECT_AFTER_CODEMIRROR_COMMAND = createCommand('SELECT_AFTER_CODEMIRROR_COMMAND');
export function registerCodeMirrorCommand(editor) {
return mergeRegister(editor.registerCommand(INSERT_CODEMIRROR_COMMAND, function () {
editor.update(function () {
var codeMirrorNode = $createCodeMirrorNode('', '');
$insertNodes([codeMirrorNode]);
});
return true;
}, COMMAND_PRIORITY_EDITOR // Priority
), editor.registerCommand(UPDATE_CODEBLOCK_LANG, function (payload) {
var codeMirrorNode = editor.getEditorState().read(function () {
var selection = $getSelection();
if ($isRangeSelection(selection)) {
if (selection.isCollapsed()) {
var node = $findMatchingParent(selection.anchor.getNode(), $isCodeMirrorNode);
return node;
} else {
var anchor = $findMatchingParent(selection.anchor.getNode(), $isCodeMirrorNode);
var focus = $findMatchingParent(selection.focus.getNode(), $isCodeMirrorNode);
if (anchor && focus && anchor === focus) {
return anchor;
}
return null;
}
}
return false;
});
if (!codeMirrorNode) {
return false;
}
// Need to defer execution due to possible transform execution order confusion from selection changes
queueMicrotask(function () {
editor.update(function () {
if ($isCodeMirrorNode(codeMirrorNode)) {
codeMirrorNode.setLang(payload.lang);
}
});
});
return true;
}, COMMAND_PRIORITY_EDITOR), editor.registerCommand(SELECT_BEFORE_CODEMIRROR_COMMAND, function (payload) {
editor.update(function () {
var node = $getNodeByKey(payload.key);
if (!node) {
return;
}
var prevNode = node.getPreviousSibling();
var sel = prevNode === null || prevNode === void 0 ? void 0 : prevNode.selectEnd();
console.info('SELECT_BEFORE_CODEMIRROR_COMMAND', prevNode, sel);
if (sel) {
$setSelection(sel);
}
editor.focus();
});
return false;
}, COMMAND_PRIORITY_EDITOR), editor.registerCommand(SELECT_AFTER_CODEMIRROR_COMMAND, function (payload) {
editor.update(function () {
var node = $getNodeByKey(payload.key);
if (!node) {
return;
}
var nextNode = node.getNextSibling();
var sel = nextNode === null || nextNode === void 0 ? void 0 : nextNode.selectStart();
console.info('SELECT_AFTER_CODEMIRROR_COMMAND', sel, nextNode, node);
if (sel) {
$setSelection(sel);
}
editor.focus();
});
return false;
}, COMMAND_PRIORITY_EDITOR));
}