New annotation API: Annotation and AnnotationFactory classes

Fleshes out ve.dm.Annotation to a class. Annotations in the linear model
will be instances of a subclass of ve.dm.Annotation. Annotations are
defined by subclassing ve.dm.Annotation and registering this subclass
with ve.dm.AnnotationFactory.

ve.dm.AnnotationFactory keeps track of which annotation classes are known,
and has code to match an HTML element to an annotation class, for use in
the converter.

Change-Id: I68802bdb8736ced1f9e04ee49c623944b448141c
This commit is contained in:
Catrope 2012-08-31 12:34:18 -07:00
parent 9ca5da44ee
commit 7fe7182f43
6 changed files with 484 additions and 7 deletions

View file

@ -76,6 +76,7 @@ class VisualEditorHooks {
'dm/ve.dm.TransactionProcessor.test.js',
'dm/ve.dm.Surface.test.js',
'dm/ve.dm.SurfaceFragment.test.js',
'dm/ve.dm.AnnotationFactory.test.js',
// VisualEditor ContentEditable Tests
'ce/ve.ce.test.js',
'ce/ve.ce.Document.test.js',

View file

@ -1,15 +1,137 @@
/**
* VisualEditor data model Annoation class.
* VisualEditor data model Annotation class.
*
* @copyright 2011-2012 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/**
* Generic DataModel annotation.
* Generic data model annotation.
*
* This is an abstract class, annotations should extend this and call this constructor from their
* constructor. You should not instantiate this class directly.
*
* Annotations in the linear model are instances of subclasses of this class. Subclasses are
* required to have a constructor with the same signature.
*
* this.htmlTagName and this.htmlAttributes are private to the base class, subclasses must not
* use them. Any information from the HTML element that is needed later should be extracted into
* this.data by overriding getAnnotationData(). Subclasses can read from this.data but must not
* write to it directly.
*
* @class
* @abstract
* @constructor
*
* @param {HTMLElement} [element] HTML element this annotation was converted from, if any
*/
ve.dm.Annotation = function VeDmAnnotation() {
ve.dm.Annotation = function VeDmAnnotation( element ) {
this.name = this.constructor.static.name; // Needed for proper hashing
this.data = {};
if ( element ) {
this.htmlTagName = element.nodeName.toLowerCase();
this.htmlAttributes = ve.getDOMAttributes( element );
this.data = this.getAnnotationData( element );
}
};
/* Static properties */
/**
* Object containing static properties. ve.inheritClass() contains special logic to make sure these
* properties are inherited by subclasses.
*/
ve.dm.Annotation.static = {};
/**
* Symbolic name for the annotation class. Must be set to a unique string by every subclass.
*/
ve.dm.Annotation.static.name = null;
/**
* Array of HTML tag names that this annotation should be a match candidate for.
* Empty array means none, null means any.
* For more information about annotation matching, see ve.dm.AnnotationFactory.
*/
ve.dm.Annotation.static.matchTagNames = null;
/**
* Array of RDFa types that this annotation should be a match candidate for.
* Empty array means none, null means any.
* For more information about annotation matching, see ve.dm.AnnotationFactory.
*/
ve.dm.Annotation.static.matchRdfaTypes = null;
/**
* Optional function to determine whether this annotation should match a given element.
* Takes an HTMLElement and returns true or false.
* This function is only called if this annotation has a chance of "winning"; see
* ve.dm.AnnotationFactory for more information about annotation matching.
* If set to null, this property is ignored. Setting this to null is not the same as unconditionally
* returning true, because the presence or absence of a matchFunction affects the annotation's
* specificity.
*
* NOTE: This function is NOT a method, within this function "this" will not refer to an instance
* of this class (or to anything reasonable, for that matter).
*/
ve.dm.Annotation.static.matchFunction = null;
/* Methods */
/**
* Get annotation data for the linear model. Called when building a new annotation from an HTML
* element.
*
* This annotation data object is completely free-form. It's stored in the linear model, it can be
* manipulated by UI widgets, and you access it as this.data in toHTML() on the way out and in
* renderHTML() for rendering. It is also the ONLY data you can reliably use in those contexts, so
* any information from the HTML element that you'll need later should be extracted into the data
* object here.
*
* @param {HTMLElement} element HTML element this annotation will represent
* @returns {Object} Annotation data
*/
ve.dm.Annotation.prototype.getAnnotationData = function ( element ) {
return {};
};
/**
* Convert this annotation back to HTML for output purposes.
*
* You should only use this.data here, you cannot reliably use any of the other properties.
* The default action is to restore the original HTML element's tag name and attributes (if this
* annotation was created based on an element). If a subclass wants to do this too (this is common),
* it should call its parent's implementation first, then manipulate the return value.
*
* @returns {Object} Object with 'tag' (tag name) and 'attributes' (object with attribute key/values)
*/
ve.dm.Annotation.prototype.toHTML = function () {
return {
'tag': this.htmlTagName || '',
'attributes': this.htmlAttributes || {}
};
};
/**
* Convert this annotation to HTML for rendering purposes. By default, this just calls toHTML(),
* but it may be customized if the rendering should be different from the output.
*
* @see ve.dm.Annotation.toHTML
* @returns {Object} Object with 'tag' (tag name) and 'attributes' (object with attribute key/values)
*/
ve.dm.Annotation.prototype.renderHTML = function () {
return this.toHTML();
};
/**
* Custom hash function for ve.getHash(). Should not be overridden by subclasses.
*/
ve.dm.Annotation.prototype.getHash = function () {
var keys = [ 'name', 'htmlTagName', 'htmlAttributes', 'data' ], obj = {}, i;
for ( i = 0; i < keys.length; i++ ) {
if ( this[keys[i]] !== undefined ) {
obj[keys[i]] = this[keys[i]];
}
}
return ve.getHash( obj );
};

View file

@ -1,26 +1,270 @@
/**
* VisualEditor data model AnnotationFactory class.
* VisualEditor AnnotationFactory class.
*
* @copyright 2011-2012 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
( function ( ve ) {
/**
* DataModel annotation factory.
* Factory for annotations.
*
* To register a new annotation type, call ve.dm.annotationFactory.register()
*
* @class
* @abstract
* @constructor
* @extends {ve.Factory}
* @extends {ve.EventEmitter}
*/
ve.dm.AnnotationFactory = function VeDmAnnotationFactory() {
ve.dm.AnnotationFactory = function () {
// Parent constructor
ve.Factory.call( this );
// [ { tagName: [annotationNamesWithoutFunc] }, { tagName: [annotationNamesWithFunc] } ]
this.annotationsByTag = [ {}, {} ];
// { matchFunctionPresence: { rdfaType: { tagName: [annotationNames] } } }
// [ { rdfaType: { tagName: [annotationNamesWithoutFunc] } }, { rdfaType: { tagName: [annotationNamesWithFunc] } ]
this.annotationsByTypeAndTag = [];
// { nameA: 0, nameB: 1, ... }
this.registrationOrder = {};
this.nextNumber = 0;
};
/* Inheritance */
ve.inheritClass( ve.dm.AnnotationFactory, ve.Factory );
/* Private helper functions */
/**
* Helper function for register(). Adds a value to the front of an array in a nested object.
* Objects and arrays are created if needed. You can specify either two or three keys and a value.
*
* Specifically:
* addType( obj, keyA, keyB, keyC, value ) does obj[keyA][keyB][keyC].unshift( value );
* addType( obj, keyA, keyB, value ) does obj[keyA][keyB].unshift( value );
*
* @param {Object} obj Object to add to
* @param {String} keyA Key into obj
* @param {String} keyB Key into obj[keyA]
* @param {String|any} keyC Key into obj[keyA][keyB], or value to add to array if value not set
* @param {any} [value] Value to add to the array
*/
function addType( obj, keyA, keyB, keyC, value ) {
if ( obj[keyA] === undefined ) {
obj[keyA] = {};
}
if ( obj[keyA][keyB] === undefined ) {
obj[keyA][keyB] = value === undefined ? [] : {};
}
if ( value !== undefined && obj[keyA][keyB][keyC] === undefined ) {
obj[keyA][keyB][keyC] = [];
}
if ( value === undefined ) {
obj[keyA][keyB].unshift( keyC );
} else {
obj[keyA][keyB][keyC].unshift( value );
}
}
/* Public methods */
/**
* Register an annotation type.
* @param {String} name Symbolic name for the annotation
* @param {ve.dm.Annotation} constructor Subclass of ve.dm.Annotation
*/
ve.dm.AnnotationFactory.prototype.register = function ( name, constructor ) {
if ( typeof name !== 'string' || name === '' ) {
throw new Error( 'Annotation names must be strings and must not be empty' );
}
// Call parent implementation
ve.Factory.prototype.register.call( this, name, constructor );
var i, j,
name = constructor.static.name,
tags = constructor.static.matchTagNames === null ? [ '' ] :
constructor.static.matchTagNames,
types = constructor.static.matchRdfaTypes === null ? [ '' ] :
constructor.static.matchRdfaTypes;
for ( i = 0; i < tags.length; i++ ) {
// +!!foo is a shorter equivalent of Number( Boolean( foo ) ) or foo ? 1 ; 0
addType( this.annotationsByTag, +!!constructor.static.matchFunction,
tags[i], name
);
}
for ( i = 0; i < types.length; i++ ) {
for ( j = 0; j < tags.length; j++ ) {
addType( this.annotationsByTypeAndTag,
+!!constructor.static.matchFunction, types[i], tags[j], name
);
}
}
this.registrationOrder[name] = this.nextNumber++;
};
/**
* Determine which annotation best matches the given element
*
* Annotation matching works as follows:
* Get all annotations whose tag and rdfaType rules match
* Rank them in order of specificity:
* * tag, rdfaType and func specified
* * rdfaType and func specified
* * tag and func specified
* * func specified
* * tag and rdfaType specified
* * rdfaType specified
* * tag specified
* * nothing specified
* If there are multiple candidates with the same specificity, they are ranked in reverse order of
* registration (i.e. if A was registered before B, B will rank above A).
* The highest-ranking annotation whose test function does not return false, wins.
*
* @param {HTMLElement} element Element to match
* @returns {String|null} Annotation type, or null if none found
*/
ve.dm.AnnotationFactory.prototype.matchElement = function ( element ) {
var i, name, ann, matches, winner, types,
tag = element.nodeName.toLowerCase(),
typeAttr = element.getAttribute( 'typeof' ) || element.getAttribute( 'rel' ),
reg = this;
function byRegistrationOrderDesc( a, b ) {
return reg.registrationOrder[b] - reg.registrationOrder[a];
}
function matchWithFunc( types, tag ) {
var i, j, matches, queue = [];
for ( i = 0; i < types.length; i++ ) {
matches = ve.getProp( reg.annotationsByTypeAndTag, 1, types[i], tag ) || [];
for ( j = 0; j < matches.length; j++ ) {
queue.push( matches[j] );
}
}
queue.sort( byRegistrationOrderDesc );
for ( i = 0; i < queue.length; i++ ) {
if ( reg.registry[queue[i]].static.matchFunction( element ) ) {
return queue[i];
}
}
return null;
}
function matchWithoutFunc( types, tag ) {
var i, j, matches, winningName = null;
for ( i = 0; i < types.length; i++ ) {
matches = ve.getProp( reg.annotationsByTypeAndTag, 0, types[i], tag ) || [];
for ( j = 0; j < matches.length; j++ ) {
if (
winningName === null ||
reg.registrationOrder[winningName] < reg.registrationOrder[matches[j]]
) {
winningName = matches[j];
}
}
}
return winningName;
}
types = typeAttr ? typeAttr.split( ' ' ) : [];
if ( types.length ) {
// func+tag+type match
winner = matchWithFunc( types, tag );
if ( winner !== null ) {
return winner;
}
// func+type match
// Only look at rules with no tag specified; if a rule does specify a tag, we've
// either already processed it above, or the tag doesn't match
winner = matchWithFunc( types, '' );
if ( winner !== null ) {
return winner;
}
}
// func+tag match
matches = ve.getProp( this.annotationsByTag, 1, tag ) || [];
// No need to sort because individual arrays in annotadtionsByTag are already sorted
// correctly
for ( i = 0; i < matches.length; i++ ) {
name = matches[i];
ann = this.registry[name];
// Only process this one if it doesn't specify types
// If it does specify types, then we've either already processed it in the
// func+tag+type step above, or its type rule doesn't match
if ( ann.static.matchRdfaTypes === null && ann.static.matchFunction( element ) ) {
return matches[i];
}
}
// func only
// We only need to get the [''][''] array because the other arrays were either
// already processed during the steps above, or have a type or tag rule that doesn't
// match this element.
// No need to sort because individual arrays in annotationsByTypeAndTag are already sorted
// correctly
matches = ve.getProp( this.annotationsByTypeAndTag, 1, '', '' ) || [];
for ( i = 0; i < matches.length; i++ ) {
if ( this.registry[matches[i]].static.matchFunction( element ) ) {
return matches[i];
}
}
// tag+type
winner = matchWithoutFunc( types, tag );
if ( winner !== null ) {
return winner;
}
// type only
// Only look at rules with no tag specified; if a rule does specify a tag, we've
// either already processed it above, or the tag doesn't match
winner = matchWithoutFunc( types, '' );
if ( winner !== null ) {
return winner;
}
// tag only
matches = ve.getProp( this.annotationsByTag, 0, tag ) || [];
// No need to track winningName because the individual arrays in annotationsByTag are
// already sorted correctly
for ( i = 0; i < matches.length; i++ ) {
name = matches[i];
ann = this.registry[name];
// Only process this one if it doesn't specify types
// If it does specify types, then we've either already processed it in the
// tag+type step above, or its type rule doesn't match
if ( ann.static.matchRdfaTypes === null ) {
return matches[i];
}
}
// Rules with no type or tag specified
// These are the only rules that can still qualify at this point, the others we've either
// already processed or have a type or tag rule that disqualifies them
matches = ve.getProp( this.annotationsByTypeAndTag, 0, '', '' ) || [];
if ( matches.length > 0 ) {
return matches[0];
}
// We didn't find anything, give up
return null;
};
ve.dm.AnnotationFactory.prototype.createFromElement = function ( element ) {
var name = this.matchElement( element );
if ( name === null ) {
return null;
} else {
return this.create( name, element );
}
};
/* Initialization */
ve.dm.annotationFactory = new ve.dm.AnnotationFactory();
} )( ve );

View file

@ -11,4 +11,5 @@
ve.dm = {
//'nodeFactory': Initialized in ve.dm.NodeFactory.js
//'converter': Initialized in ve.dm.Converter.js
//'annotationFactory': Initialized in ve.dm.AnnotationFactory.js
};

View file

@ -0,0 +1,108 @@
/**
* VisualEditor AnnotationFactory tests.
*
* @copyright 2011-2012 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
QUnit.module( 've.dm.AnnotationFactory' );
/* Stubs */
function checkForPickMe( element ) {
return element.hasAttribute( 'pickme' );
}
ve.dm.StubNothingSetAnnotation = function VeDmStubNothingSetAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubNothingSetAnnotation, ve.dm.Annotation );
ve.dm.StubNothingSetAnnotation.static.name = 'stubnothingset';
ve.dm.StubSingleTagAnnotation = function VeDmStubSingleTagAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubSingleTagAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTagAnnotation.static.name = 'stubsingletag';
ve.dm.StubSingleTagAnnotation.static.matchTagNames = ['a'];
ve.dm.StubSingleTypeAnnotation = function VeDmStubSingleTypeAnnotation( element ) {
ve.dm.Annotation.call( this, 'stubsingletype', element );
};
ve.inheritClass( ve.dm.StubSingleTypeAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTypeAnnotation.static.name = 'stubsingletype';
ve.dm.StubSingleTypeAnnotation.static.matchRdfaTypes = ['mw:foo'];
ve.dm.StubSingleTagAndTypeAnnotation = function VeDmStubSingleTagAndTypeAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubSingleTagAndTypeAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTagAndTypeAnnotation.static.name = 'stubsingletagandtype';
ve.dm.StubSingleTagAndTypeAnnotation.static.matchTagNames = ['a'];
ve.dm.StubSingleTagAndTypeAnnotation.static.matchRdfaTypes = ['mw:foo'];
ve.dm.StubFuncAnnotation = function VeDmStubFuncAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubFuncAnnotation, ve.dm.Annotation );
ve.dm.StubFuncAnnotation.static.name = 'stubfunc';
ve.dm.StubFuncAnnotation.static.matchFunction = checkForPickMe;
ve.dm.StubSingleTagAndFuncAnnotation = function VeDmStubSingleTagAndFuncAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubSingleTagAndFuncAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTagAndFuncAnnotation.static.name = 'stubsingletagandfunc';
ve.dm.StubSingleTagAndFuncAnnotation.static.matchTagNames = ['a'];
ve.dm.StubSingleTagAndFuncAnnotation.static.matchFunction = checkForPickMe;
ve.dm.StubSingleTypeAndFuncAnnotation = function VeDmStubSingleTypeAndFuncAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubSingleTypeAndFuncAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTypeAndFuncAnnotation.static.name = 'stubsingletypeandfunc';
ve.dm.StubSingleTypeAndFuncAnnotation.static.matchRdfaTypes = ['mw:foo'];
ve.dm.StubSingleTypeAndFuncAnnotation.static.matchFunction = checkForPickMe;
ve.dm.StubSingleTagAndTypeAndFuncAnnotation = function VeDmStubSingleTagAndTypeAndFuncAnnotation( element ) {
ve.dm.Annotation.call( this, element );
};
ve.inheritClass( ve.dm.StubSingleTagAndTypeAndFuncAnnotation, ve.dm.Annotation );
ve.dm.StubSingleTagAndTypeAndFuncAnnotation.static.name = 'stubsingletagandtypeandfunc';
ve.dm.StubSingleTagAndTypeAndFuncAnnotation.static.matchTagNames = ['a'];
ve.dm.StubSingleTagAndTypeAndFuncAnnotation.static.matchRdfaTypes = ['mw:foo'];
ve.dm.StubSingleTagAndTypeAndFuncAnnotation.static.matchFunction = checkForPickMe;
/* Tests */
QUnit.test( 'matchElement', 9, function ( assert ) {
var factory = new ve.dm.AnnotationFactory(), element;
element = document.createElement( 'a' );
assert.deepEqual( factory.matchElement( element ), null, 'matchElement() returns null if registry empty' );
factory.register( 'stubnothingset', ve.dm.StubNothingSetAnnotation );
factory.register( 'stubsingletag', ve.dm.StubSingleTagAnnotation );
factory.register( 'stubsingletype', ve.dm.StubSingleTypeAnnotation );
factory.register( 'stubsingletagandtype', ve.dm.StubSingleTagAndTypeAnnotation );
factory.register( 'stubfunc', ve.dm.StubFuncAnnotation );
factory.register( 'stubsingletagandfunc', ve.dm.StubSingleTagAndFuncAnnotation );
factory.register( 'stubsingletypeandfunc', ve.dm.StubSingleTypeAndFuncAnnotation );
factory.register( 'stubsingletagandtypeandfunc', ve.dm.StubSingleTagAndTypeAndFuncAnnotation );
element = document.createElement( 'b' );
assert.deepEqual( factory.matchElement( element ), 'stubnothingset', 'nothingset matches anything' );
element.setAttribute( 'rel', 'mw:foo' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletype', 'type-only match' );
element = document.createElement( 'a' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletag', 'tag-only match' );
element.setAttribute( 'rel', 'mw:foo' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletagandtype', 'tag and type match' );
element.setAttribute( 'pickme', 'true' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletagandtypeandfunc', 'tag, type and func match' );
element.setAttribute( 'rel', 'mw:bar' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletagandfunc', 'tag and func match' );
element = document.createElement( 'b' );
element.setAttribute( 'pickme', 'true' );
assert.deepEqual( factory.matchElement( element ), 'stubfunc', 'func-only match' );
element.setAttribute( 'rel', 'mw:foo' );
assert.deepEqual( factory.matchElement( element ), 'stubsingletypeandfunc', 'type and func match' );
} );

View file

@ -116,6 +116,7 @@
<script src="dm/ve.dm.TransactionProcessor.test.js"></script>
<script src="dm/ve.dm.Surface.test.js"></script>
<script src="dm/ve.dm.SurfaceFragment.test.js"></script>
<script src="dm/ve.dm.AnnotationFactory.test.js"></script>
<script src="ce/ve.ce.test.js"></script>
<script src="ce/ve.ce.Document.test.js"></script>
<script src="ce/ve.ce.NodeFactory.test.js"></script>