You are viewing a plain text version of this content. The canonical link for it is here.
Posted to xap-commits@incubator.apache.org by bb...@apache.org on 2006/07/12 19:56:32 UTC

svn commit: r421395 - /incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js

Author: bbuffone
Date: Wed Jul 12 12:56:32 2006
New Revision: 421395

URL: http://svn.apache.org/viewvc?rev=421395&view=rev
Log:
Checking in the first version of the xModify against the HTML DOM.

Also added and fixed xModify jsunit tests for both 
xmodify against reagular dom and HTML dom

Sample application to test and demo how to use xModify against the 
HTML dom

Added:
    incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js

Added: incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js?rev=421395&view=auto
==============================================================================
--- incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js (added)
+++ incubator/xap/trunk/src/xap/xml/xmodify/CommandDirective.js Wed Jul 12 12:56:32 2006
@@ -0,0 +1,963 @@
+/*
+ * Copyright  2006 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+ 
+Xap.require("google.dom");
+ 
+ /**
+ * @fileoverview An object embodying a particular operation (e.g., <code>append</code>) to be performed 
+ * on a targetted part of the UI document (as specifically using either 
+ * XPath or a Xap-specific syntax wrappering <code>getElementById()</code>.<b> 
+ * 
+ * @class  Command directives point to a document; they're 
+ * handed a valid XPath expression (or the syntax "id('ID_STRING')" which is
+ * used to select the node[s] in the document ("target nodes" hereafter) we'll 
+ * want to change; a prespecified action is performed on them on "execute".  
+ * This is reminiscent of LISP's lambda/mapping functionality, in that a 
+ * particular directive is set (e.g., append a new child we've specified) 
+ * and then that action is applied to the targets. Directives include any arguments
+ * used in the operation, as specified in the defining tags' bodies.
+ * <br/>
+ * Here are some examples: <br/>
+ * <br/>
+ * Example 1: insert a new address record after the first record with id 0: <br>
+ * <code><br/>
+ * &nbsp;&nbsp;&nbsp; &lt;xm:insert-after select="id('0')"><br/> 
+ * &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;     &lt;address id="1" /&gt;<br/>
+ * &nbsp;&nbsp;&nbsp;  &lt;/xm:insert-after&gt;
+ * <br/></code><br/><br/>
+ * Example 2: set the 'grade' and 'nickname' attributes of a 
+ * particular element named 'foo'<br>
+ * <code><br/>
+ * &nbsp;&nbsp;&nbsp; &lt;xm:set-attribute select="/baz/bar/foo"&gt;<br/>
+ * &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;attribute name="grade" value="A1" /&gt;<br/>
+ * &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;attribute name="nickname" value="B1" /&gt;<br/>
+ * &nbsp;&nbsp;&nbsp; &lt;/xm:set-attribute&gt;
+ * <br/></code>
+ * @version modeled after Java $Revision: 1.18 $
+ * @author xap@hisown.com
+ */
+//----------------------------------------------------------------------
+// Constructors.
+//----------------------------------------------------------------------
+
+CommandDirective = function(elemDirectiveElement)
+{
+
+    /* Call our superclass' UpdateDirective */
+    UpdateDirective.call( this, elemDirectiveElement );  
+
+    this._selectAttr = elemDirectiveElement.getAttribute("select");
+    this._commandArguments = elemDirectiveElement.childNodes ;
+    // Will set later, just before we execute this directive:
+    this._commandTargets = null ;
+
+    /* For mandatory arguments, like for set-attributes */
+    if ((this._commandArguments.length == 0) &&
+	   (this._strType == "set-attribute") ) /* We'll replace this with a mustHaveArgs() func */
+	{
+	    throw new XmodifyException(XmodifyException.COMMAND_EXPECTS_ONE_ARG,"set-attribute") ;
+     
+	}
+}
+
+
+
+/**
+ * Executes this command directive against the passed-in context node---
+ * First find the targets of the operation on construction, then execute
+ * the callback corresponding to the directive.
+ * @param uiDocumentNode The UI document, presumably including nodes that 
+ * will be selected to be the object of the directive.
+ * @throws XmodifyException
+ */
+CommandDirective.prototype.execute = function (uiDocumentNode)
+{
+    this._commandTargets 
+        = this._selectMatchingNodes(uiDocumentNode,this._selectAttr ) ;
+
+    var directiveType 
+        = UpdateDirective.getDirectiveTypeAsInt(this._strType) ;
+    
+    this._bHtmlDocument = !(uiDocumentNode instanceof Document);   
+        
+    // handle "no targets" case---
+    var needsTarget = CommandDirective._mustHaveTarget(directiveType) ;
+    if ( needsTarget && ( this._commandTargets.length == 0 ) ){
+        throw new 
+            XmodifyException(
+                XmodifyException.ZERO_RESULTS, 
+                this._selectAttr
+                                );
+    }
+    
+    /* @TODO: Switch on type, use ints, not strs */
+    switch (directiveType) {
+        case UpdateDirective.DIRECTIVE_APPEND:
+		  this._handleAppend(uiDocumentNode);
+		  break;
+        case UpdateDirective.DIRECTIVE_SET_ATTRIBUTE:
+		  this._handleSetAttribute(uiDocumentNode);
+		  break;
+        case UpdateDirective.DIRECTIVE_REMOVE_ELEMENT:
+		  this._handleRemoveElement(uiDocumentNode);
+		  break;
+        case UpdateDirective.DIRECTIVE_REMOVE_ATTRIBUTE:
+		  this._handleRemoveAttribute(uiDocumentNode);
+          break;     
+        case UpdateDirective.DIRECTIVE_INSERT_BEFORE: 
+		  this._handleInsertBefore(uiDocumentNode);
+		  break;   
+        case UpdateDirective.DIRECTIVE_INSERT_AFTER: 
+          this._handleInsertAfter(uiDocumentNode);
+          break;                
+        case UpdateDirective.DIRECTIVE_REPLACE: 
+          this._handleReplace(uiDocumentNode);
+          break;   
+        case UpdateDirective.DIRECTIVE_REMOVE_CHILDREN: 
+          this._handleRemoveChildren(uiDocumentNode);
+          break;   
+        case UpdateDirective.DIRECTIVE_CLONE: 
+          this._handleClone(uiDocumentNode);
+          break;                            	                               
+        default: 
+	       Xmodify.s_log.debug("Unhandled command : "+this._strType);
+    } /* end switch */
+} /* end execute */
+
+
+
+/**
+ * Does the desired operation require a target node to work?
+ * @return true if this directive must have a target node.
+ * @param nDirectiveType an integer from UpdateDirective's 
+ * constants corresponding to our allowed operations (append, replace,...)
+ * @see UpdateDirective#DIRECTIVE_NAMES
+**/
+CommandDirective._mustHaveTarget = function(nDirectiveType){
+//Don't need target for create-document...any others?
+    var needs = (nDirectiveType != UpdateDirective.DIRECTIVE_CREATE_DOCUMENT) ;
+    return needs ;
+
+}
+
+
+/**
+ * @private
+ * Select the nodes in the document
+ * that match the select criteria given.
+ **/
+CommandDirective.prototype._selectMatchingNodes = function(uiDocumentNode,selectString){
+ 
+    var targetNodesArray= new Array(0) ;
+    var localSelectString = selectString ;
+ 
+    //handle the id('xxx') syntax instead of full xpath
+    if ( selectString && selectString.indexOf("id(")==0){
+	   var id = selectString.substring(3);
+	   var aposIndex = id.indexOf("'");
+	   var lastAposIndex = id.lastIndexOf("'");
+       id = id.substring(aposIndex+1,lastAposIndex);
+	   var target = uiDocumentNode.getElementById(id);
+       if( target && typeof target != "undefined"){
+    	   targetNodesArray.push(target) ;	
+       }
+    } else {
+    	var currentContext =   new google.ExprContext(uiDocumentNode) ;
+    	var parsedXPathExpr = google.xpathParse(localSelectString) ;
+	
+    	var targetNodes = parsedXPathExpr.evaluate( currentContext );
+    	var targetNodesArray = targetNodes.nodeSetValue();	
+    }
+	
+    return targetNodesArray ;
+}
+
+
+/**
+ * Appends the nodes held in <code>this._commandArguments</code> to the nodes held in
+ * <code>this._commandTargets</code>.
+ * @throw XmodifyException
+**/
+CommandDirective.prototype._handleAppend = function(uiDocumentNode)
+{
+
+    var targetNodes = this._commandTargets ;
+    var elemsToAppend = this._commandArguments;      
+    Xmodify.s_log.debug (
+			 "We have " 
+			 + elemsToAppend.length 
+			 + " children  to append to " 
+			 + this._selectAttr 
+			 + ": " 
+			 + this.formatDocument(uiDocumentNode)
+			 );
+  							
+    for (var i = 0; i < targetNodes.length ; i ++)
+    {
+
+	/* Must CLONE elemsToAppend - otherwise elemsToAppend.length changes 
+	 * while in loop..
+	 */
+
+	var currentNode = targetNodes[i];
+	if (currentNode.nodeType == google.DOM_DOCUMENT_NODE ){
+		if (elemsToAppend.length != 1)
+		    {
+			throw new XmodifyException(XmodifyException.SET_ROOT_ELEMENT_EXPECTS_ONE_ARG);
+		    }
+
+		Xmodify.s_log.debug (
+                "We have 1 elem to append as new root : " 
+                + elemsToAppend[0]
+                );
+		currentNode.setRootElement(elemsToAppend[0]);
+         
+    } else if (currentNode.nodeType == google.DOM_ELEMENT_NODE ){
+		for (var j = 0; j < elemsToAppend.length; j++){
+			try {
+                 if (currentNode instanceof google.XNode){
+			        currentNode.appendChild(elemsToAppend[j].deepClone(false)); 
+                 } else if (this._bHtmlDocument){
+			        currentNode.appendChild(this.makeNodeHTML(elemsToAppend[j])); 
+			     }
+			} 
+			catch (e) { 
+			    if (e.toString().indexOf('MsgId:idConflict')!= -1)
+				{
+				    alert("rethrowing exception");
+				    throw (e);
+				}
+			    else
+				{
+				    Xmodify.s_log.debug ("Exception: " + e + " This could be because of a duplicate id issue despite deepClone"); }
+			}
+		    } ;/* end for j.. */
+
+	    } /* end if Element */
+          else {
+		      throw new XmodifyException(XmodifyException.CANT_BLANK_TO_NODE_TYPE, "append", currentNode.nodeType) ;
+        }
+    } /* end for i < targetNodes.length...*/
+
+    Xmodify.s_log.debug("Post Append uIDoc: \n " 
+			+ this.formatDocument(uiDocumentNode) 
+			);
+
+
+
+}  /* end handleAppend */
+
+
+/**
+ * Sets attributes of the nodes held in <code>this._commandArguments</code> 
+ * according to the name/value pairs held as attributes in
+ * <code>this._commandTargets</code>, e.g. &lt;xm:set-attribute name=&quot;width&quot; value=&quot;30px&quot;/&gt;
+ * @throws XmodifyException
+**/
+CommandDirective.prototype._handleSetAttribute = function(uiDocumentNode)
+{
+
+    /* @TODO: Validity checks */
+    var attrsToSet = this._commandArguments;
+    var targetNodes = this._commandTargets ;
+
+    if (!targetNodes.length){
+        /* Throw an exception? Alert? */
+    }
+
+    for (var i = 0; i < targetNodes.length; i ++){
+        var currentNode = targetNodes[i];
+
+        if (currentNode.nodeType == google.DOM_ELEMENT_NODE  ){
+			for (var j = 0 ; j < attrsToSet.length; j++){
+		    	try {             
+					var attrToSet = attrsToSet[j];
+					if (attrToSet.getLocalName 
+			    		// a little roundabout, just a way of seeing if the node local
+			    		// name is "attribute"
+			    		&& UpdateDirective.getDirectiveTypeAsInt(attrToSet.getLocalName()) == UpdateDirective.DIRECTIVE_ATTRIBUTE 
+                      ){              
+						var name = attrToSet.getAttribute('name');
+						var val = attrToSet.getAttribute('value');
+						currentNode.setAttribute(name, val);
+			    	} else {
+			    		throw new XmodifyException(
+			    				XmodifyException.ATTRIBUTE_ARGUMENT_NOT_ATTRIB_DIRECTIVE, 
+			    				attrToSet.getLocalName()
+			    				);
+					}
+
+		    	} catch (e) { alert(j + " " + e.message); }
+
+		} /* end for */
+	}
+	else
+	{
+            throw new XmodifyException(XmodifyException.CANT_BLANK_TO_NODE_TYPE, "Set-Attribute", currentNode.nodeType) ;
+	}
+    }; /* End for */
+
+    Xmodify.s_log.debug("Post Set-Attr: \n " + this.formatDocument(uiDocumentNode) );
+ 
+} /* end handleSetAttribute */
+
+
+
+/**
+ * Removes the nodes held in <code>this._commandArguments</code> (and 
+ * their subtrees, if any).
+ * @throw XmodifyException
+**/
+CommandDirective.prototype._handleRemoveElement = function(uiDocumentNode)
+{
+    /** Removing an element from the XPATH specified  **/
+    var xpathRemoved = this._selectAttr;
+    var targetNodes = this._commandTargets ;  
+
+    Xmodify.s_log.debug('removing the element at XPath : ' 
+            + xpathRemoved + " Results: " 
+            + targetNodes.length
+            );
+
+
+    try{
+    for (var i = 0; i < targetNodes.length ; i ++)
+        {
+        /* 2DO: Handle text nodes */
+        var elem = targetNodes[i];
+   
+        if (!elem) 
+            {
+            /* Could be null - e.g. if a firstTextChild did not exist -
+             * in which case, we just continue.. 
+             */
+            continue;
+            }
+  
+        /* This may issue #1 - I return getFirstTextChild - that's good.
+           BUT, I can't getClass on it to have it return "Text". in fact, it
+           DOES show me the text content, but getClass is not defined.. 
+           I can't use getParent either.. although in the Java code you do both.
+           I assume it's a string. Can I simply use setFirst.. instead?
+        */
+         if (elem.nodeType == google.DOM_ELEMENT_NODE)
+            {
+            var parent = elem.parentNode;
+
+            if (parent)
+                {
+                parent.removeChild(elem);
+                }
+            else
+                { /* Parent is NULL - remove document altogether !*/
+                uiDocumentNode.setRootElement(null);
+                }
+            }
+        else if (elem.nodeType == google.DOM_TEXT_NODE)
+            {
+            Xmodify.s_log.debug ("Removing text node: "+elem.nodeValue());
+            var parent = elem.parentNode;
+            if (parent)
+                {
+                parent.removeChild(elem.getFirstTextChild());
+                }
+            }
+        else { alert ("element " + elem.nodeType + " not supported");
+                throw ("element " + elem.nodeType + " not supported");
+        }
+
+        }; /* end for */
+
+    } catch (e) {alert(e.message);}
+        Xmodify.s_log.debug("Post Remove: " + this.formatDocument(uiDocumentNode));
+
+} /* end handleRemove */
+
+/**
+ * Removes all the children for a given node---simpler than remove-element,
+ * since that one must handle text nodes specially, and contend with the 
+ * possibility that an element to be removed has no parent to remove it.
+ * @see CommandDirective#_handleRemoveElement
+ * @throws XmodifyException
+ * @param uidDocument---complete xml for the layout, to date also includes the
+ * specs for the modification directives handles by this class's instances....
+ * @author mturyn
+**/
+CommandDirective.prototype._handleRemoveChildren = function(uiDocumentNode){
+//Xmodify.DEBUG=true;
+    /** Removing an element from the XPATH specified  **/
+    var parentSelector = this._selectAttr;
+    var targetNodes = this._commandTargets ;  
+
+    Xmodify.s_log.debug('Removing the children of nodes for XPath : ' 
+            + parentSelector + " Results: " 
+            + targetNodes.length
+            );
+
+
+    try{
+        for (var i = 0; i < targetNodes.length ; i ++){
+            var currentParent = targetNodes[i];
+
+            if (!currentParent){
+                /* Could be null - e.g. if a firstTextChild did not exist -
+                * in which case, we just continue.. 
+                */
+                continue;
+            }
+
+            // If no children, no operation:
+            if ( currentParent.childNodes == null
+                || currentParent.childNodes.length==0
+                    ){
+                continue ;
+            }
+            var lastIndex = currentParent.childNodes.length ;
+            // childNodes will shrink with each removal:
+            while(--lastIndex > -1 ){
+                var currentChild = currentParent.childNodes[lastIndex] ;
+                currentParent.removeChild(currentChild) ;
+            } // end loop over all children to remove for a given parent
+        } // end loop over all parents selected
+
+    } catch (e) {
+        alert(e.message);
+    } 
+        Xmodify.s_log.debug("Post Remove: " + this.formatDocument(uiDocumentNode));
+//Xmodify.DEBUG=false ;        
+
+} /* end _handleRemoveChildren */
+
+
+/**
+ * Removes the attributes specified by <code>this._commandArguments</code> from the
+ * nodes in <code>this._commandTargets</code> 
+ * @throws XmodifyException
+ * @param uidDocument---complete xml for the layout, to date also includes the
+ * specs for the modification directives handles by this class's instances....
+ * @author mturyn
+**/
+CommandDirective.prototype._handleRemoveAttribute = function(uiDocumentNode){
+
+    /* @TODO: Validity checks */
+    var attrsToRemove = this._commandArguments ;
+    var targetNodes = this._commandTargets ;  
+
+    Xmodify.s_log.debug("Pre Remove-Attr: "+this._selectAttr+"\n " + this.formatDocument(uiDocumentNode) );
+
+    for (var i = 0; i < targetNodes.length ; i ++){
+        var currentNode = targetNodes[i];
+
+        if (currentNode.nodeType == google.DOM_ELEMENT_NODE){
+            for (var j = 0 ; j < attrsToRemove.length ; j++) {
+                try {
+             
+              var attrToRemove = attrsToRemove[j];
+              if (attrToRemove.getLocalName 
+               // a little roundabout, just a way of seeing if the node local
+               // name is "attribute"
+               && (UpdateDirective.getDirectiveTypeAsInt(attrToRemove.getLocalName()) 
+                   == UpdateDirective.DIRECTIVE_ATTRIBUTE 
+                   )
+               ){             
+               var name = attrToRemove.getAttribute('name');
+               currentNode.removeAttribute(name);
+              } else {
+                throw new XmodifyException(XmodifyException.ATTRIBUTE_ARGUMENT_NOT_ATTRIB_DIRECTIVE, attrToSet.getLocalName());
+              }
+
+          } catch (e) { alert(j + " " + e.message); }
+
+         } // (End iterating over nodes from which to remove attribute[s].)
+     }   // This was an element
+     else {
+         throw new XmodifyException(XmodifyException.CANT_BLANK_TO_NODE_TYPE, "Set-Attribute", currentNode.nodeType) ;
+     }
+    }; // (End iterating over attribute[s] to remove.)
+
+    Xmodify.s_log.debug("Post Remove-Attr: \n " + this.formatDocument(uiDocumentNode) );
+ 
+} /* end handleRemoveAttribute */
+
+
+
+
+
+/**
+ * A helper method for the <code>insert-before</code>  
+ * and <code>insert-after</code>  directives:
+ * @deprecated
+ * @param index
+ * @param parent
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype.insertCommandArgumentsAt 
+    = function(index,parent,contextNode, xpathResultIndex)
+{
+	var arrArguments = this._commandArguments ;
+    for (var ii=0; ii<arrArguments.length; ++i ) {
+
+	// unresolved argument: (arbitrary xml | String | CloneDirective |
+	// ValueOfDirective)*
+	var arg = arrArguments[ii] ;
+	// Just try it for XNode and descendants so far:
+	if (arg instanceof google.XNode){
+		parent.insertChildAt(index, arg);
+	} else {
+		throw new XmodifyException("Can't insert the desired element, can only insert XNode (or descendant) instances so far.") ;
+	}	
+	
+	
+	
+/*
+	if (arg instanceof CommandDirective) {
+	    var resolvedArgs = this.evaluateArgumentDirective(
+							    arg, contextNode, environment);
+	    if (resolvedArgs != null) {
+		for (var e2 = resolvedArgs.elements(); e2.hasMoreElements();) {
+		    var resolvedArg = e2.nextElement();
+
+		    if (resolvedArg instanceof Element) {
+				parent.insertChildAt(index, resolvedArg);
+				index++;
+		    } else if (resolvedArg instanceof String) {
+				parent.insertChildAt(index, resolvedArg);
+				index++;
+		    } else {
+				parent.insertChildAt(index, resolvedArg.toString());
+				index++;
+		    }
+		}
+	    }
+	} else {
+	    if (arg instanceof Element) {
+		if (xpathResultIndex > 0) {
+		    var copy = this.cloneElementWithClientServerIdMatching(
+									  arg, true, // deep
+									  false // withIds
+											);
+		    parent.insertChildAt(index, copy);
+		} else {
+		    parent.insertChildAt(index, arg);
+		}
+		index++;
+	    } else if (arg instanceof String) {
+			parent.insertChildAt(index, arg);
+			index++;
+	    } else {
+			parent.insertChildAt(index, arg.toString());
+			index++;
+	    }
+	}
+	*/
+    } // End of for() loop over elements to append in
+}
+
+
+
+
+/**
+ * A helper method to for the <code>insert-before</code>  directive:
+ * 
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._handleInsertBefore = function(contextNode){
+
+    /* @TODO: Validity checks */
+    var targetNodes = this._commandTargets ;  
+
+ 
+    for (var i = 0; i < targetNodes.length ; i ++){
+        var currentNode = targetNodes[i] ;
+        var parent = null ;
+        var index = -1 ;
+
+        parent = currentNode.parentNode ;
+
+        if (currentNode.nodeType == google.DOM_ELEMENT_NODE ||
+         	currentNode.nodeType == google.DOM_TEXT_NODE) {
+            if ( parent == null ) {
+                throw new XmodifyException(
+                        XmodifyException.INVALID_INSERT_AFTER_BECAUSE_OF_PARENT, 
+                        "'undefined'"
+                            )
+            }
+        } else if (currentNode.nodeType == google.DOM_ATTRIBUTE_NODE) {
+            //TODO we might want to make it work in the future.
+            // to make it work for attributes we'll need additional
+            // API on the Element: setAttributeAt
+            throw new XmodifyException(
+                        XmodifyException.CHILDREN_CANT_BE_ADDED, 
+                        parent.nodeName 
+                            ) ; 
+        } else {
+            throw new XmodifyException(
+                    XmodifyException.INVALID_INSERT_BEFORE_BECAUSE_OF_PARENT,
+                    currentNode.nodeName
+                                        ) ;
+        }
+
+        // Do the simple thing, at this point:
+        Xmodify.s_log.debug("Pre insert-before: <" + currentNode.nodeName+"/>:\n" + this.formatDocument(parent));
+        
+        this._insertCommandArgumentsBefore(parent,currentNode) ;
+
+        Xmodify.s_log.debug("Post insert-before:  <" + currentNode.nodeName+"/>:\n" + this.formatDocument(parent) );
+
+
+        //this.insertCommandArgumentsAt(index, parent, contextNode, i);
+    }
+
+}
+
+/**
+ * A helper method to for the <code>insert-after</code>  directive:
+ * 
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._handleInsertAfter = function(contextNode){
+
+    /* @TODO: Validity checks */
+    var targetNodes = this._commandTargets ;  
+ 
+    for (var i = 0; i < targetNodes.length ; i ++){
+        var currentNode = targetNodes[i] ;
+        var parent = null ;
+        var index = -1 ;
+
+        parent = currentNode.parentNode ;
+
+        if (currentNode.nodeType == google.DOM_ELEMENT_NODE ||
+         	currentNode.nodeType == google.DOM_TEXT_NODE) {
+            if ( parent == null ) {
+                throw new XmodifyException(
+                        XmodifyException.INVALID_INSERT_AFTER_BECAUSE_OF_PARENT, 
+                        "'undefined'"
+                            )
+            }
+        } else if (currentNode.nodeType == google.DOM_ATTRIBUTE_NODE) {
+            //TODO we might want to make it work in the future.
+            // to make it work for attributes we'll need additional
+            // API on the Element: setAttributeAt
+            throw new XmodifyException(
+                        XmodifyException.CHILDREN_CANT_BE_ADDED, 
+                        parent.nodeName 
+                            ) ; 
+        } else {
+            throw new XmodifyException(
+                    XmodifyException.INVALID_INSERT_BEFORE_BECAUSE_OF_PARENT,
+                    currentNode.nodeName
+                                        ) ;
+        }
+
+        // Do the simple thing, at this point:
+        Xmodify.s_log.debug("Pre insert-after: <" + currentNode.nodeName+"/>:\n" + this.formatDocument(parent));
+        
+        this._insertCommandArgumentsAfter(parent,currentNode) ;
+
+        Xmodify.s_log.debug("Post insert-after:  <" + currentNode.nodeName+"/>:\n" + this.formatDocument(parent) );
+
+
+        //this.insertCommandArgumentsAt(index, parent, contextNode, i);
+    }
+
+}
+
+/**
+ * A helper method for the <code>insert-before</code>  directive: 
+ * @param parent
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._insertCommandArgumentsAfter 
+    = function(parent,oldChild){
+    var arrArguments = this._commandArguments ;
+        for (var ii=0; ii<arrArguments.length; ++ii ) {
+        // unresolved argument: (arbitrary xml | String | CloneDirective |
+        // ValueOfDirective)*
+        var newChild = arrArguments[ii] ;
+        // Just try it for XNode and descendants so far:
+        if (oldChild instanceof google.XNode){
+            var nextOldChild = oldChild.nextSibling ;
+            if (true||nextOldChild != null){
+                parent.insertBefore(
+                            newChild.deepClone(false), 
+                            nextOldChild
+                                );
+            } else {
+                // If there is no next sibling before which to insert,
+                // we can just append it to the end of the child list:
+                parent.appendChild(newChild.deepClone(false));                
+            }
+        } else if (this._bHtmlDocument){
+            var nextOldChild = oldChild.nextSibling ;
+            if (true||nextOldChild != null){
+                parent.insertBefore(
+                             this.makeNodeHTML(newChild), 
+                             nextOldChild
+                             );
+            } else {
+                // If there is no next sibling before which to insert,
+                // we can just append it to the end of the child list:
+                parent.appendChild(this.makeNodeHTML(newChild));                
+            }
+        } else {
+            throw new XmodifyException("Can't insert the desired element before the indicated element, that target is not an XNode (or subclass tree) instance.") ;
+        }   
+    }
+}
+
+/**
+ * A helper method for the <code>insert-before</code>  directive: 
+ * @param parent
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._insertCommandArgumentsBefore
+    = function(parent,oldChild){
+    var arrArguments = this._commandArguments ;
+        for (var ii=0; ii<arrArguments.length; ++ii ) {
+        // unresolved argument: (arbitrary xml | String | CloneDirective |
+        // ValueOfDirective)*
+        var newChild = arrArguments[ii] ;
+        // Just try it for XNode and descendants so far:
+        if (oldChild instanceof google.XNode){
+            parent.insertBefore(
+                            newChild.deepClone(false), 
+                            oldChild
+                                );
+        } else if (this._bHtmlDocument){
+            parent.insertBefore(
+                             this.makeNodeHTML(newChild), 
+                             oldChild
+                             );
+        } else {
+            throw new XmodifyException("Can't insert the desired element before the indicated element, that target is not an XNode (or subclass tree) instance.") ;
+        }   
+    }
+}
+
+
+
+
+	
+/**
+ * A helper method for the <code>replace</code>  directive;
+ * implemented here as a (transactionally-wrappered) <code>insert-before</code>
+ * the element to replace, followed by its <code>remove</code>:
+ * 
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._handleReplace = function(contextNode){
+
+ 	/* @TODO: Validity checks */
+    var targetNodes = this._commandTargets ;  
+
+  	if (!targetNodes.length)
+    {
+        /* Throw an exception? Alert? */
+    } 	
+
+	Xmodify.s_log.debug("Pre replacement:\n" + this.formatDocument(contextNode));
+
+    for (var ii=0; ii<targetNodes.length; ++ii ) {
+		// unresolved argument: (arbitrary xml | String | CloneDirective |
+		// ValueOfDirective)*
+		var oldChild = targetNodes[ii] ;
+		// Just try it for XNode and descendants so far:
+		if (oldChild instanceof google.XNode || this._bHtmlDocument){
+			Xmodify.s_log.debug("Pre replacing <" + oldChild.nodeName+"/>:\n" + this.formatDocument(oldChild.parentNode));
+			this._replaceWithCommandArguments(oldChild) ;
+			Xmodify.s_log.debug("Post replacing:  <" + oldChild.nodeName+"/>:\n" + this.formatDocument(oldChild.parentNode) );	
+		} else {
+			throw new XmodifyException(XmodifyException.CANNOT_REPLACE__ORIGINAL_INVALID,""+oldChild) ;
+		}	
+    }
+	Xmodify.s_log.debug("Post replacement:\n" + this.formatDocument(contextNode));
+    
+
+
+	//Xmodify.s_log.debug("Post replacement:  <" + contextNode.nodeName+"/>:\n" + this.formatDocument(contextNode) );
+	
+}
+
+
+/**
+ * A helper method for the <code>insert-before</code>  directive: 
+ * @param parent
+ * @param contextNode
+ * @throws XmodifyException
+ */
+CommandDirective.prototype._replaceWithCommandArguments  =  function(oldChild){
+    //Xmodify.DEBUG=true;
+    // Do the simple thing, at this point:
+    var parent = oldChild.parentNode ;       
+    var arrArguments = this._commandArguments ;
+    var newChild=null ;
+    try {
+     for (var ii=0; ii<arrArguments.length; ++ii ) {
+         // unresolved argument: (arbitrary xml | String | CloneDirective |
+         // ValueOfDirective)
+         newChild = arrArguments[ii] ;
+         // Just try it for XNode and descendants so far:
+         if (oldChild instanceof google.XNode){
+          Xmodify.s_log.debug(
+            "Pre insertion of " + this.formatDocument(newChild)+"\nbefore\n" 
+            + this.formatDocument(oldChild)
+            + this.formatDocument(parent) 
+                                ) ;
+          try {
+              parent.insertBefore(
+                         newChild.deepClone(false), 
+                         oldChild
+                         );
+          } catch (insertionException){
+              throw new XmodifyException(XmodifyException.CANNOT_REPLACE__INSERTION,newChild.nodeName,""+insertionException);
+          }
+          Xmodify.s_log.debug(
+            "Post insertion of " + this.formatDocument(newChild) +"\nbefore\n" 
+            + this.formatDocument(oldChild)
+            + this.formatDocument(parent) 
+                                ) ;                             
+         } else if (this._bHtmlDocument){
+              Xmodify.s_log.debug(
+                "Pre insertion of " + this.formatDocument(newChild)+"\nbefore\n" 
+                + this.formatDocument(oldChild)
+                + this.formatDocument(parent) 
+                                    ) ;
+              try {
+                  parent.insertBefore(
+                             this.makeNodeHTML(newChild), 
+                             oldChild
+                             );
+                             
+                 // alert("parent.insertBefore(after");
+              } catch (insertionException){
+                  throw new XmodifyException(XmodifyException.CANNOT_REPLACE__INSERTION,newChild.nodeName,""+insertionException);
+              }
+              Xmodify.s_log.debug(
+                "Post insertion of " + this.formatDocument(newChild) +"\nbefore\n" 
+                + this.formatDocument(oldChild)
+                + this.formatDocument(parent) 
+                                    );                             
+         } else {
+            throw new XmodifyException(XmodifyException.CANNOT_REPLACE,oldChild.nodeName,newChild.nodeName,"unknown cause");     
+         }     
+     } // end of the iteration over all replacement nodes
+     try {
+         // all the new nodes have been inserted, so now take out the old node:
+         parent.removeChild(oldChild) ;
+     } catch (removalException){
+         // Better if we could attempt to back off all the 
+         // changes, but not yet:
+         throw new XmodifyException(XmodifyException.CANNOT_REPLACE__REMOVAL,oldChild.nodeName,""+removalException);          
+     }
+
+    } catch(replacementException){
+     throw new XmodifyException(XmodifyException.CANNOT_REPLACE,
+                       oldChild.nodeName,
+                       newChild.nodeName,
+                       ""+replacementException
+                       );     
+    } finally {
+  Xmodify.s_log.debug(
+    "Post all insertions and removals composited into replacement:"
+    + '\n'+ this.formatDocument(parent) 
+                                ) ;
+    	//Xmodify.DEBUG=false;
+    }// end of 'try'/catch  blocks around iteration over nodes to to replace in
+        
+} // end of _replaceWithCommandArguments()
+
+
+
+/**
+ * Handles cloning declaration directive
+ * @throw
+ */
+CommandDirective.prototype._handleClone = function(uiDocumentNode){
+
+    this._clones = new Array(this._commandTargets.length) ;
+
+
+
+    for (var ll=0; ll<this._commandTargets.length; ++ll) {
+        var toClone = this._commandTargets[ll] ;
+        if (toClone.nodeType == google.DOM_ELEMENT_NODE) {
+            var cloned = toClone.deepClone(false) ;
+            this._clones[ll] = clone ;
+        } else {
+            throw new XmodifyException(
+                    XmodifyException.CANT_BLANK_TO_NODE_TYPE, 
+                    "Clone", 
+                    currentNode.nodeType
+                                        ) ;
+
+        }
+    }
+}
+
+/**
+ * Format the supplied document into a pretty printed output string
+ * Used in debug statements only.
+ * @param document 
+ * @return Formattes string 
+ */
+CommandDirective.prototype.formatDocument = function(inputDocument){
+    try{
+        //try to format catch exception.
+        return inputDocument;//.toXml(true);
+    }catch(genericException){
+        return inputDocument;
+    }
+}
+
+/*
+ * TODO - Look for possible better place to stick this.
+ */
+CommandDirective.prototype.makeNodeHTML = function(node){
+    //create the element
+    var htmlNode = document.createElement(node.getLocalName());
+    
+    //copy over the attributes
+	for( var i=0; i<node.attributes.length; i++ ) {
+	    var key = node.attributes[i].nodeName;
+	    var value = node.attributes[i].nodeValue;
+        htmlNode.setAttribute(key, value);
+    }
+    
+    //clone the children.
+	for ( var i = 0; i < node.getChildCount(); i++ ) {
+		var child = node.getChildAt(i);
+		if( child.nodeType == google.DOM_TEXT_NODE && child.nodeValue) {
+			htmlNode.appendChild(document.createTextNode(child.nodeValue));
+		}else{
+		    htmlNode.appendChild(this.makeNodeHTML(child));
+		}
+	}
+    
+    //return the new html node
+    return htmlNode;
+}
+
+//End of CommandDirective
+
+    
\ No newline at end of file