Skip to content

Commit

Permalink
Fix toggling styles on collapsed selections with $patchStyleText (fac…
Browse files Browse the repository at this point in the history
  • Loading branch information
birtles authored Feb 17, 2023
1 parent dfb0383 commit ee32d77
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

import {$createLinkNode} from '@lexical/link';
import {$createHeadingNode} from '@lexical/rich-text';
import {$patchStyleText} from '@lexical/selection';
import {
$getSelectionStyleValueForProperty,
$patchStyleText,
} from '@lexical/selection';
import {
$createParagraphNode,
$createTextNode,
Expand Down Expand Up @@ -2862,4 +2865,50 @@ describe('$patchStyleText', () => {
'<p dir="ltr"><span data-lexical-text="true">text</span></p>',
);
});

test('can toggle a style on a collapsed selection', async () => {
const editor = createTestEditor();
const element = document.createElement('div');
editor.setRootElement(element);

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

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

const text = $createTextNode('text');
paragraph.append(text);

setAnchorPoint({
key: text.getKey(),
offset: 0,
type: 'text',
});
setFocusPoint({
key: text.getKey(),
offset: 0,
type: 'text',
});

const selection = $getSelection() as RangeSelection;
$patchStyleText(selection, {'text-emphasis': 'filled'});

expect(
$getSelectionStyleValueForProperty(selection, 'text-emphasis', ''),
).toEqual('filled');

$patchStyleText(selection, {'text-emphasis': null});

expect(
$getSelectionStyleValueForProperty(selection, 'text-emphasis', ''),
).toEqual('');

$patchStyleText(selection, {'text-emphasis': 'filled'});

expect(
$getSelectionStyleValueForProperty(selection, 'text-emphasis', ''),
).toEqual('filled');
});
});
});
5 changes: 4 additions & 1 deletion packages/lexical-selection/src/lexical-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,13 +281,16 @@ export function $patchStyleText(
if (selection.isCollapsed()) {
const styles = getStyleObjectFromCSS(selection.style);
Object.entries(patch).forEach(([key, value]) => {
if (value !== null) {
if (value === null) {
delete styles[key];
} else {
styles[key] = value;
}
return styles;
});
const style = getCSSFromStyleObject(styles);
selection.setStyle(style);
CSS_TO_STYLES.set(style, styles);
return;
}

Expand Down

0 comments on commit ee32d77

Please sign in to comment.