diff --git a/packages/lexical-selection/src/lexical-node.ts b/packages/lexical-selection/src/lexical-node.ts index 22074d1fd6e..850978a325b 100644 --- a/packages/lexical-selection/src/lexical-node.ts +++ b/packages/lexical-selection/src/lexical-node.ts @@ -289,22 +289,33 @@ export function $patchStyleText( ) => string) >, ): void { - if (selection.isCollapsed() && $isRangeSelection(selection)) { - $patchStyle(selection, patch); - } else { - $forEachSelectedTextNode((textNode) => { - $patchStyle(textNode, patch); - }); - } + $forEachSelectedTextNode((textNode) => { + $patchStyle(textNode, patch); + }); } +/** + * @param fn - The function to apply to each selected TextNode. + * @param includeIfCollapsed - Whether to include the TextNode if the selection is collapsed. Defaults to false. + */ export function $forEachSelectedTextNode( fn: (textNode: TextNode) => void, + includeIfCollapsed = false, ): void { const selection = $getSelection(); if (!$isRangeSelection(selection)) { return; } + if (selection.isCollapsed()) { + if (!includeIfCollapsed) { + return; + } + const node = selection.anchor.getNode(); + if ($isTextNode(node)) { + fn(node); + } + return; + } const selectedNodes = selection.getNodes(); const selectedNodesLength = selectedNodes.length; const {anchor, focus} = selection;