Skip to content

Commit

Permalink
Merge pull request #51 from benmccormick/bugfix/count-subchild-length
Browse files Browse the repository at this point in the history
Don't ignore lengths of subchilds when calculating entity lengths
  • Loading branch information
Kadi Kraman authored Jan 9, 2020
2 parents 8dc9c09 + 2d6787f commit 3f02b0d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
9 changes: 8 additions & 1 deletion src/mdToDraftjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,14 @@ const parseMdLine = (line, existingEntities, extraStyles = {}) => {
};

const getRawLength = children =>
children.reduce((prev, current) => prev + (current.value ? current.value.length : 0), 0);
children.reduce((prev, current) => {
if (current.value) {
return prev + current.value.length;
} else if (current.children && current.children.length) {
return prev + getRawLength(current.children);
}
return prev;
}, 0);

const addLink = child => {
const entityKey = Object.keys(entityMap).length;
Expand Down
41 changes: 39 additions & 2 deletions test/mdToDraftjs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ describe('mdToDraftjs', () => {
mdToDraftjs(markdown).should.deep.equal(expectedDraftjs);
});

it('converts two styles applied to the a link correctly', () => {
it('converts two styles applied outside a link correctly', () => {
const markdown = '__*[label](http://example.com/here)*__';
const expectedDraftjs = {
blocks: [
Expand All @@ -196,7 +196,7 @@ describe('mdToDraftjs', () => {
],
inlineStyleRanges: [
{
length: 0,
length: 5,
offset: 0,
style: 'BOLD'
},
Expand All @@ -221,6 +221,43 @@ describe('mdToDraftjs', () => {
resultDraftJs.should.deep.equal(expectedDraftjs);
});

it('converts a style applied inside a link correctly', () => {
const markdown = '[la**b**el](http://example.com/here)';
const expectedDraftjs = {
blocks: [
{
text: 'label',
type: 'unstyled',
depth: 0,
entityRanges: [
{
key: 0,
length: 5,
offset: 0
}
],
inlineStyleRanges: [
{
length: 1,
offset: 2,
style: 'BOLD'
}
]
}
],
entityMap: {
0: {
type: 'LINK',
mutability: 'MUTABLE',
data: { url: 'http://example.com/here' }
}
}
};

const resultDraftJs = mdToDraftjs(markdown);
resultDraftJs.should.deep.equal(expectedDraftjs);
});

it('converts several paragraphs to markdown correctly', () => {
const markdown =
'*First __content__* block.\n*Second __content__* block.\n*Third __content__* block.';
Expand Down

0 comments on commit 3f02b0d

Please sign in to comment.