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

Commit

Permalink
Add handling of whitespaces after the inline style change
Browse files Browse the repository at this point in the history
  • Loading branch information
Axel Wahlen committed Jun 25, 2018
1 parent 2df3609 commit 60407de
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
26 changes: 26 additions & 0 deletions src/modifiers/__test__/changeCurrentInlineStyle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,30 @@ describe("changeCurrentInlineStyle", () => {
)
);
});
it("handles a style terminator properly", () => {
const text = "foo **bar** baz";
const editorState = createEditorState(text, []);
const matchArr = ["**bar** ", "bar", " "];
matchArr.index = 4;
matchArr.input = text;
const newEditorState = changeCurrentInlineStyle(
editorState,
matchArr,
"BOLD"
);
expect(newEditorState).not.toEqual(editorState);
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
rawContentState(
"foo bar baz",
[
{
length: 3,
offset: 4,
style: "BOLD",
},
],
"BOLD"
)
);
});
});
29 changes: 25 additions & 4 deletions src/modifiers/changeCurrentInlineStyle.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,26 @@ const changeCurrentInlineStyle = (editorState, matchArr, style) => {
focusOffset,
});

const inlineStyles = [];
const markdownCharacterLength = (matchArr[0].length - matchArr[1].length) / 2;
// check if match contains a terminator group at the end
let matchTerminatorLength = 0;
if (matchArr.length == 3) {
matchTerminatorLength = matchArr[2].length;
}

const markdownCharacterLength =
(matchArr[0].length - matchArr[1].length - matchTerminatorLength) / 2;

const inlineStyles = [];
let newContentState = currentContent;

// remove markdown delimiter at end
newContentState = Modifier.removeRange(
newContentState,
wordSelection.merge({
anchorOffset: wordSelection.getFocusOffset() - markdownCharacterLength,
anchorOffset:
wordSelection.getFocusOffset() -
markdownCharacterLength -
matchTerminatorLength,
})
);

Expand All @@ -50,11 +60,22 @@ const changeCurrentInlineStyle = (editorState, matchArr, style) => {
newContentState,
wordSelection.merge({
anchorOffset: index,
focusOffset: focusOffset - markdownCharacterLength * 2,
focusOffset:
focusOffset - markdownCharacterLength * 2 - matchTerminatorLength,
}),
style
);

// Check if a terminator exists and re-add it after the styled text
if (matchTerminatorLength > 0) {
newContentState = Modifier.insertText(
newContentState,
afterSelection,
matchArr[2]
);
afterSelection = newContentState.getSelectionAfter();
}

const newEditorState = EditorState.push(
editorState,
newContentState,
Expand Down

0 comments on commit 60407de

Please sign in to comment.