Skip to content

Commit

Permalink
[lexical-selection] Bug Fix: Selection is removed when changing style…
Browse files Browse the repository at this point in the history
… of 2 different nodes (#6223)

Co-authored-by: Nikolaos Zigopis <[email protected]>
Co-authored-by: sahejkm <[email protected]>
  • Loading branch information
3 people authored Jun 3, 2024
1 parent 723285e commit 10c687d
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
$setSelection,
ElementNode,
LexicalEditor,
LexicalNode,
ParagraphNode,
RangeSelection,
TextNode,
Expand Down Expand Up @@ -3075,4 +3076,51 @@ describe('$patchStyleText', () => {
expect(color).toEqual('');
});
});

test('preserve backward selection when changing style of 2 different text nodes', async () => {
const editor = createTestEditor();

const element = document.createElement('div');

editor.setRootElement(element);

editor.update(() => {
const root = $getRoot();

const paragraph = $createParagraphNode();
root.append(paragraph);

const firstText = $createTextNode('first ').setFormat('bold');
paragraph.append(firstText);

const secondText = $createTextNode('second').setFormat('italic');
paragraph.append(secondText);

$setAnchorPoint({
key: secondText.getKey(),
offset: 'sec'.length,
type: 'text',
});

$setFocusPoint({
key: firstText.getKey(),
offset: 'fir'.length,
type: 'text',
});

const selection = $getSelection();

$patchStyleText(selection!, {'font-size': '11px'});

const [newAnchor, newFocus] = selection!.getStartEndPoints()!;

const newAnchorNode: LexicalNode = newAnchor.getNode();
expect(newAnchorNode.getTextContent()).toBe('sec');
expect(newAnchor.offset).toBe('sec'.length);

const newFocusNode: LexicalNode = newFocus.getNode();
expect(newFocusNode.getTextContent()).toBe('st ');
expect(newFocus.offset).toBe(0);
});
});
});
6 changes: 5 additions & 1 deletion packages/lexical-selection/src/lexical-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,11 @@ export function $patchStyleText(
// the entire first node isn't selected, so split it
firstNode = firstNode.splitText(startOffset)[1];
startOffset = 0;
anchor.set(firstNode.getKey(), startOffset, 'text');
if (isBefore) {
anchor.set(firstNode.getKey(), startOffset, 'text');
} else {
focus.set(firstNode.getKey(), startOffset, 'text');
}
}

$patchStyle(firstNode as TextNode, patch);
Expand Down

0 comments on commit 10c687d

Please sign in to comment.