Rewrite DocumentFragment getAnnotationsFromRange method

Write unit tests for getAnnotationsFromRange

Change-Id: I82ff15e97378c07e5c555a72231da4161a72993c
This commit is contained in:
Rob Moen 2012-05-11 16:14:46 -07:00
parent 5b9a2645a6
commit bd9a0b6fba
2 changed files with 101 additions and 0 deletions

View file

@ -202,6 +202,50 @@ ve.dm.DocumentFragment.prototype.getAnnotationsFromOffset = function( offset, by
return [];
};
/**
* Gets an array of common annnotations across a range.
*
* @method
* @param {Integer} offset Offset to get annotations for
* @returns {Object[]} A copy of all annotation objects offset is covered by
*/
ve.dm.DocumentFragment.prototype.getAnnotationsFromRange = function( range ) {
range.normalize();
var length = range.getLength(),
elementsCount = 0,
charAnnotationsObj,
annotations = [],
map = {},
aObj;
for (var i=range.start; i<range.end;i++) {
if ( ve.dm.Document.isElementData( this.data, i ) ) {
elementsCount++;
continue;
}
charAnnotationsObj = this.data[i][1];
for ( aObj in charAnnotationsObj ) {
hash = $.toJSON( aObj );
if ( hash in map ) {
// increase the count for the annotation
map[hash][1]++;
} else {
// save the annotation and start the count at 1
map[hash] = [charAnnotationsObj[aObj], 1];
}
}
}
// build array of common annotations
for ( var hash in map ) {
if ( map[hash][1] === length - elementsCount ) {
annotations.push( map[hash][0] );
}
}
return annotations;
};
/* Inheritance */
ve.extendClass( ve.dm.DocumentFragment, ve.Document );

View file

@ -157,3 +157,60 @@ test( 'getAnnotationsFromOffset', 1, function() {
}
} );
test( 'getAnnotationsFromRange', 1, function() {
var fragment,
range,
cases = [
{
'msg': 'all bold',
'data': [
['a', { '{"type:"bold"}': { 'type': 'bold' } } ],
['b', { '{"type:"bold"}': { 'type': 'bold' } } ]
],
'expected': [ { 'type': 'bold' } ]
},
{
'msg': 'bold and italic',
'data': [
['a', { '{"type":"bold"}': { 'type': 'bold' }, '{"type":"italic"}': { 'type': 'italic'} } ],
['b', { '{"type":"bold"}': { 'type': 'bold' }, '{"type":"italic"}': { 'type': 'italic'} } ]
],
'expected': [ { 'type': 'bold' }, { 'type': 'italic' } ]
},
{
'msg': 'bold and italic',
'data': [
['a', { '{"type":"bold"}': { 'type': 'bold' }, '{"type":"italic"}': { 'type': 'italic'} } ],
['b', { '{"type":"bold"}': { 'type': 'bold' }, '{"type":"italic"}': { 'type': 'italic'}, '{"type":"underline"}': { 'type': 'underline'} } ]
],
'expected': [ { 'type': 'bold' }, { 'type': 'italic' } ]
},
{
'msg': 'all different',
'data': [
['a', { '{"type:"bold"}': { 'type': 'bold' } } ],
['b', { '{"type:"italic"}': { 'type': 'italic' } } ]
],
'expected': []
},
{
'msg': 'none',
'data': ['a', 'b'],
'expected': []
}
];
expect( cases.length );
for ( var i=0; i<cases.length; i++ ) {
fragment = new ve.dm.DocumentFragment ( cases[i].data );
range = new ve.Range( 0, fragment.getData().length );
annotations = fragment.getAnnotationsFromRange( range );
deepEqual(
annotations, cases[i].expected, cases[i].msg
);
}
});