From 33bbcd9c98ce97eead13199dbb6680a3e5b77b48 Mon Sep 17 00:00:00 2001 From: Trevor Parscal Date: Wed, 2 Nov 2011 22:00:25 +0000 Subject: [PATCH] Copying serializer code to VisualEditor extension --- modules/es/es.AnnotationSerializer.js | 60 +++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 modules/es/es.AnnotationSerializer.js diff --git a/modules/es/es.AnnotationSerializer.js b/modules/es/es.AnnotationSerializer.js new file mode 100644 index 0000000000..c81cfabd7a --- /dev/null +++ b/modules/es/es.AnnotationSerializer.js @@ -0,0 +1,60 @@ +/** + * Creates an annotation renderer object. + * + * @class + * @constructor + * @property annotations {Object} List of annotations to be applied + */ +es.AnnotationSerializer = function() { + this.annotations = {}; +}; + +/* Static Methods */ + +/** + * Adds a set of annotations to be inserted around a range of text. + * + * Insertions for the same range will be nested in order of declaration. + * @example + * stack = new es.AnnotationSerializer(); + * stack.add( new es.Range( 1, 2 ), '[', ']' ); + * stack.add( new es.Range( 1, 2 ), '{', '}' ); + * // Outputs: "a[{b}]c" + * console.log( stack.render( 'abc' ) ); + * + * @param range {es.Range} Range to insert text around + * @param pre {String} Text to insert before range + * @param post {String} Text to insert after range + */ +es.AnnotationSerializer.prototype.add = function( range, pre, post ) { + // TODO: Once we are using Range objects, we should do a range.normalize(); here + if ( !( range.start in this.annotations ) ) { + this.annotations[range.start] = [pre]; + } else { + this.annotations[range.start].push( pre ); + } + if ( !( range.end in this.annotations ) ) { + this.annotations[range.end] = [post]; + } else { + this.annotations[range.end].unshift( post ); + } +}; + +/** + * Renders annotations into text. + * + * @param text {String} Text to apply annotations to + * @returns {String} Wrapped text + */ +es.AnnotationSerializer.prototype.render = function( text ) { + var out = ''; + for ( var i = 0, length = text.length; i <= length; i++ ) { + if ( i in this.annotations ) { + out += this.annotations[i].join( '' ); + } + if ( i < length ) { + out += text[i]; + } + } + return out; +};