Skip to content
This repository was archived by the owner on Oct 11, 2022. It is now read-only.

Commit 60407de

Browse files
author
Axel Wahlen
committed
Add handling of whitespaces after the inline style change
1 parent 2df3609 commit 60407de

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

src/modifiers/__test__/changeCurrentInlineStyle-test.js

+26
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,30 @@ describe("changeCurrentInlineStyle", () => {
5757
)
5858
);
5959
});
60+
it("handles a style terminator properly", () => {
61+
const text = "foo **bar** baz";
62+
const editorState = createEditorState(text, []);
63+
const matchArr = ["**bar** ", "bar", " "];
64+
matchArr.index = 4;
65+
matchArr.input = text;
66+
const newEditorState = changeCurrentInlineStyle(
67+
editorState,
68+
matchArr,
69+
"BOLD"
70+
);
71+
expect(newEditorState).not.toEqual(editorState);
72+
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
73+
rawContentState(
74+
"foo bar baz",
75+
[
76+
{
77+
length: 3,
78+
offset: 4,
79+
style: "BOLD",
80+
},
81+
],
82+
"BOLD"
83+
)
84+
);
85+
});
6086
});

src/modifiers/changeCurrentInlineStyle.js

+25-4
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,26 @@ const changeCurrentInlineStyle = (editorState, matchArr, style) => {
1717
focusOffset,
1818
});
1919

20-
const inlineStyles = [];
21-
const markdownCharacterLength = (matchArr[0].length - matchArr[1].length) / 2;
20+
// check if match contains a terminator group at the end
21+
let matchTerminatorLength = 0;
22+
if (matchArr.length == 3) {
23+
matchTerminatorLength = matchArr[2].length;
24+
}
25+
26+
const markdownCharacterLength =
27+
(matchArr[0].length - matchArr[1].length - matchTerminatorLength) / 2;
2228

29+
const inlineStyles = [];
2330
let newContentState = currentContent;
2431

2532
// remove markdown delimiter at end
2633
newContentState = Modifier.removeRange(
2734
newContentState,
2835
wordSelection.merge({
29-
anchorOffset: wordSelection.getFocusOffset() - markdownCharacterLength,
36+
anchorOffset:
37+
wordSelection.getFocusOffset() -
38+
markdownCharacterLength -
39+
matchTerminatorLength,
3040
})
3141
);
3242

@@ -50,11 +60,22 @@ const changeCurrentInlineStyle = (editorState, matchArr, style) => {
5060
newContentState,
5161
wordSelection.merge({
5262
anchorOffset: index,
53-
focusOffset: focusOffset - markdownCharacterLength * 2,
63+
focusOffset:
64+
focusOffset - markdownCharacterLength * 2 - matchTerminatorLength,
5465
}),
5566
style
5667
);
5768

69+
// Check if a terminator exists and re-add it after the styled text
70+
if (matchTerminatorLength > 0) {
71+
newContentState = Modifier.insertText(
72+
newContentState,
73+
afterSelection,
74+
matchArr[2]
75+
);
76+
afterSelection = newContentState.getSelectionAfter();
77+
}
78+
5879
const newEditorState = EditorState.push(
5980
editorState,
6081
newContentState,

0 commit comments

Comments
 (0)