Skip to content

Commit

Permalink
Merge pull request #29 from triptease/overlapping-styles
Browse files Browse the repository at this point in the history
fix overlapping styles bug
  • Loading branch information
kadikraman authored Mar 20, 2018
2 parents 08e4632 + 5ba159f commit 0eca2c1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/draftjsToMd.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ function fixWhitespacesInsideStyle(text, style) {
`${prefix}${symbol}${bodyTrimmed}${symbol}${postfix}`);
}

function getInlineStyleRangesByLength(inlineStyleRanges) {
return [...inlineStyleRanges].sort((a, b) => b.length - a.length);
}

function draftjsToMd(raw, extraMarkdownDict) {
const markdownDict = { ...defaultMarkdownDict, ...extraMarkdownDict };
let returnString = '';
Expand All @@ -119,8 +123,10 @@ function draftjsToMd(raw, extraMarkdownDict) {
returnString += block.text.split('').reduce((text, currentChar, index) => {
let newText = text;

const sortedInlineStyleRanges = getInlineStyleRangesByLength(block.inlineStyleRanges);

// find all styled at this character
const stylesStartAtChar = block.inlineStyleRanges
const stylesStartAtChar = sortedInlineStyleRanges
.filter(range => range.offset === index)
.filter(range => markdownDict[range.style]); // disregard styles not defined in the md dict

Expand Down
25 changes: 25 additions & 0 deletions test/draftjsToMd.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,31 @@ describe('draftjsToMd', () => {
draftjsToMd(raw).should.equal(expectedMarkdown);
});

it('converts overlapping styles correctly, whether or not the "longer" one is first', () => {
const raw = {
blocks: [{
text: 'I start with italic bold and end with only bold.',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [
{
offset: 0,
length: 24,
style: 'ITALIC'
},
{
offset: 0,
length: 48,
style: 'BOLD'
},
],
entityRanges: []
}]
};
const expectedMarkdown = '__*I start with italic bold* and end with only bold.__';
draftjsToMd(raw).should.equal(expectedMarkdown);
});

it('converts the last word correctly if it is styled', () => {
const raw = {
blocks: [{
Expand Down

0 comments on commit 0eca2c1

Please sign in to comment.