Skip to content

Commit

Permalink
Minor refactoring in LexicalLineBreakNode (facebook#5455)
Browse files Browse the repository at this point in the history
  • Loading branch information
thorn0 authored and amanharwara committed Jan 18, 2024
1 parent 57b0449 commit d29f195
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions packages/lexical/src/nodes/LexicalLineBreakNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,7 @@ export class LineBreakNode extends LexicalNode {
static importDOM(): DOMConversionMap | null {
return {
br: (node: Node) => {
const parentElement = node.parentElement;
// If the <br> is the only child, then skip including it
let firstChild;
let lastChild;
if (
parentElement !== null &&
((firstChild = parentElement.firstChild) === node ||
((firstChild as Text).nextSibling === node &&
(firstChild as Text).nodeType === DOM_TEXT_TYPE &&
((firstChild as Text).textContent || '').match(
/^( |\t|\r?\n)+$/,
) !== null)) &&
((lastChild = parentElement.lastChild) === node ||
((lastChild as Text).previousSibling === node &&
(lastChild as Text).nodeType === DOM_TEXT_TYPE &&
((lastChild as Text).textContent || '').match(
/^( |\t|\r?\n)+$/,
) !== null))
) {
if (isOnlyChild(node)) {
return null;
}
return {
Expand Down Expand Up @@ -106,3 +88,31 @@ export function $isLineBreakNode(
): node is LineBreakNode {
return node instanceof LineBreakNode;
}

function isOnlyChild(node: Node): boolean {
const parentElement = node.parentElement;
if (parentElement !== null) {
const firstChild = parentElement.firstChild!;
if (
firstChild === node ||
(firstChild.nextSibling === node && isWhitespaceDomTextNode(firstChild))
) {
const lastChild = parentElement.lastChild!;
if (
lastChild === node ||
(lastChild.previousSibling === node &&
isWhitespaceDomTextNode(lastChild))
) {
return true;
}
}
}
return false;
}

function isWhitespaceDomTextNode(node: Node): boolean {
return (
node.nodeType === DOM_TEXT_TYPE &&
/^( |\t|\r?\n)+$/.test(node.textContent || '')
);
}

0 comments on commit d29f195

Please sign in to comment.