Skip to content

Commit

Permalink
Fix position calc
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Apr 4, 2019
1 parent 96d85e7 commit 936cfcd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/rich-text/src/apply-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,25 @@ export function applyFormat(
};
}
} else {
// Determine the highest position the new format can be inserted at.
let position = +Infinity;

for ( let index = startIndex; index < endIndex; index++ ) {
if ( newFormats[ index ] ) {
newFormats[ index ] = newFormats[ index ]
.filter( ( { type } ) => type !== format.type );

const length = newFormats[ index ].length;

if ( length < position ) {
position = length;
}
} else {
newFormats[ index ] = [];
position = 0;
}
}

const position = Math.min(
newFormats[ startIndex ].length,
newFormats[ endIndex - 1 ].length
);

for ( let index = startIndex; index < endIndex; index++ ) {
newFormats[ index ].splice( position, 0, format );
}
Expand Down
16 changes: 16 additions & 0 deletions packages/rich-text/src/test/apply-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ describe( 'applyFormat', () => {
expect( getSparseArrayLength( result.formats ) ).toBe( 3 );
} );

it( 'should apply format around existing format with break', () => {
const record = {
formats: [ , [ em ], , [ em ] ],
text: 'test',
};
const expected = {
...record,
formats: [ , [ strong, em ], [ strong ], [ strong, em ] ],
};
const result = applyFormat( deepFreeze( record ), strong, 1, 4 );

expect( result ).toEqual( expected );
expect( result ).not.toBe( record );
expect( getSparseArrayLength( result.formats ) ).toBe( 3 );
} );

it( 'should apply format crossing existing format', () => {
const record = {
formats: [ , , , , [ em ], [ em ], [ em ], , , , , , , ],
Expand Down

0 comments on commit 936cfcd

Please sign in to comment.