Author: mikesamuel
Date: Fri Dec 12 16:50:24 2008
New Revision: 3132

Modified:
    trunk/src/com/google/caja/parser/quasiliteral/CajitaRewriter.java
    trunk/src/com/google/caja/parser/quasiliteral/DefaultValijaRewriter.java
    trunk/src/com/google/caja/parser/quasiliteral/Rule.java
    trunk/src/com/google/caja/plugin/bridal.js
    trunk/src/com/google/caja/plugin/domita.js
    trunk/tests/com/google/caja/plugin/domita_test_untrusted.html
    trunk/tests/com/google/caja/plugin/jsunit.js

Log:
Issue 10266  http://codereview.appspot.com/10266
Implement cloneNode for DOMita.

Adds cloneNode code to DOMita and implements a cloneNode operation in
bridal to work around problems in IE and to copy over custom
properties an dattributes.

[email protected]


Modified: trunk/src/com/google/caja/parser/quasiliteral/CajitaRewriter.java
==============================================================================
--- trunk/src/com/google/caja/parser/quasiliteral/CajitaRewriter.java    
(original)
+++ trunk/src/com/google/caja/parser/quasiliteral/CajitaRewriter.java   Fri  
Dec 12 16:50:24 2008
@@ -2086,7 +2086,7 @@
          Map<String, ParseTreeNode> bindings = matchSingleMap(node);
          if (bindings != null) {
            StringLiteral key = (StringLiteral) bindings.get("key");
-          ParseTreeNode val = (ParseTreeNode) bindings.get("val");
+          ParseTreeNode val = bindings.get("val");
            return substV(
                "key", key,
                "val", expand(nymize(val, key.getUnquotedValue(), "lit"),  
scope, mq));

Modified:  
trunk/src/com/google/caja/parser/quasiliteral/DefaultValijaRewriter.java
==============================================================================
---  
trunk/src/com/google/caja/parser/quasiliteral/DefaultValijaRewriter.java        
 
(original)
+++  
trunk/src/com/google/caja/parser/quasiliteral/DefaultValijaRewriter.java        
 
Fri Dec 12 16:50:24 2008
@@ -1386,7 +1386,7 @@
          Map<String, ParseTreeNode> bindings = matchSingleMap(node);
          if (bindings != null) {
            StringLiteral key = (StringLiteral) bindings.get("key");
-          ParseTreeNode val = (ParseTreeNode) bindings.get("val");
+          ParseTreeNode val = bindings.get("val");
            return substSingleMap(
                key,
                expand(nymize(val, key.getUnquotedValue(), "lit"), scope,  
mq));

Modified: trunk/src/com/google/caja/parser/quasiliteral/Rule.java
==============================================================================
--- trunk/src/com/google/caja/parser/quasiliteral/Rule.java     (original)
+++ trunk/src/com/google/caja/parser/quasiliteral/Rule.java     Fri Dec 12  
16:50:24 2008
@@ -362,7 +362,7 @@
    /**
     * <tt>substSingleMap(k, v)</tt> should be equivalent to<pre>
     * QuasiBuilder.substV(
-   *     "({...@key: @val})",
+   *     "({&#64;key: @val})",
     *     "key", k,
     *     "val", v)</pre>
     * but currently isn't.
@@ -382,7 +382,7 @@

    /**
     * <tt>matchSingleMap(node) != null</tt> should be equivalent to<pre>
-   * QuasiBuilder.match("({...@key: @val})", node)</pre>
+   * QuasiBuilder.match("({&#64;key: @val})", node)</pre>
     * but currently isn't.
     * <p>
     * TODO(erights): figure out why not, and fix if appropriate.

Modified: trunk/src/com/google/caja/plugin/bridal.js
==============================================================================
--- trunk/src/com/google/caja/plugin/bridal.js  (original)
+++ trunk/src/com/google/caja/plugin/bridal.js  Fri Dec 12 16:50:24 2008
@@ -20,6 +20,8 @@
   *
   * @author [email protected]
   * @author [email protected]
+ * @provides bridal
+ * @requires ___, cajita, document, html, navigator
   */

  var bridal = (function() {
@@ -46,22 +48,21 @@
     * W3C <code>Element::addEventListener</code> and
     * IE <code>Element::attachEvent</code>.
     *
-   * @param element a native DOM element.
-   * @param type a string identifying the event type.
-   * @param handler a function acting as an event handler.
-   * @param useCapture whether the user wishes to initiate capture.
+   * @param {HTMLElement} element a native DOM element.
+   * @param {string} type a string identifying the event type.
+   * @param {boolean Element::function (event)} handler an event handler.
+   * @param {boolean} useCapture whether the user wishes to initiate  
capture.
     */
    function addEventListener(element, type, handler, useCapture) {
      if (features.attachEvent) {
        // TODO(ihab.awad): How do we emulate 'useCapture' here?
        element.attachEvent('on' + type, handler);
      } else {
-      element.addEventListener(
-          type, handler,
-          useCapture === void 0 ? void 0 : Boolean(useCapture));
+      // FF2 fails if useCapture not passed or is not a boolean.
+      element.addEventListener(type, handler, useCapture);
      }
    }
-
+
    /**
     * Remove an event listener function from an element.
     *
@@ -82,7 +83,147 @@
        element.removeEventListener(type, handler, useCapture);
      }
    }
-
+
+  /**
+   * Clones a node per {...@code Node.clone()}.
+   * <p>
+   * Returns a duplicate of this node, i.e., serves as a generic copy
+   * constructor for nodes. The duplicate node has no parent;
+   * (parentNode is null.).
+   * <p>
+   * Cloning an Element copies all attributes and their values,
+   * including those generated by the XML processor to represent
+   * defaulted attributes, but this method does not copy any text it
+   * contains unless it is a deep clone, since the text is contained
+   * in a child Text node. Cloning an Attribute directly, as opposed
+   * to be cloned as part of an Element cloning operation, returns a
+   * specified attribute (specified is true). Cloning any other type
+   * of node simply returns a copy of this node.
+   * <p>
+   * Note that cloning an immutable subtree results in a mutable copy,
+   * but the children of an EntityReference clone are readonly. In
+   * addition, clones of unspecified Attr nodes are specified. And,
+   * cloning Document, DocumentType, Entity, and Notation nodes is
+   * implementation dependent.
+   *
+   * @param {boolean} deep If true, recursively clone the subtree
+   * under the specified node; if false, clone only the node itself
+   * (and its attributes, if it is an Element).
+   *
+   * @return {Node} The duplicate node.
+   */
+  function cloneNode(node, deep) {
+    var clone;
+    if (!document.all) {  // Not IE 6 or IE 7
+      clone = node.cloneNode(deep);
+    } else {
+      clone = constructClone(node, deep);
+    }
+    fixupClone(node, clone);
+    return clone;
+  }
+
+  var endsWith__ = /__$/;
+  function constructClone(node, deep) {
+    var clone;
+    if (node.nodeType === 1) {
+      // From  
http://blog.pengoworks.com/index.cfm/2007/7/16/IE6--IE7-quirks-with-cloneNode-and-form-elements
+      //     It turns out IE 6/7 doesn't properly clone some form elements
+      //     when you use the cloneNode(true) and the form element is a
+      //     checkbox, radio or select element.
+      // JQuery provides a clone method which attempts to fix this and an  
issue
+      // with event listeners.  According to the source code for JQuery's  
clone
+      // method ( http://docs.jquery.com/Manipulation/clone#true ):
+      //     IE copies events bound via attachEvent when
+      //     using cloneNode. Calling detachEvent on the
+      //     clone will also remove the events from the orignal
+      // We do not need to deal with XHTML DOMs and so can skip the clean  
step
+      // that jQuery does.
+      var tagDesc = node.tagName;
+      // Copying form state is not strictly mentioned in DOM2's spec of
+      // cloneNode, but all implementations do it.  The value copying
+      // can be interpreted as fixing implementations' failure to have
+      // the value attribute "reflect" the input's value as determined by  
the
+      // value property.
+      switch (node.tagName) {
+        case 'INPUT':
+          tagDesc = '<input name="' + html.escapeAttrib(node.name)
+              + '" type="' + html.escapeAttrib(node.type)
+              + '" value="' + html.escapeAttrib(node.defaultValue) + '"'
+              + (node.defaultChecked ? ' checked="checked">' : '>');
+          break;
+        case 'OPTION':
+          tagDesc = '<option '
+              + (node.defaultSelected ? ' selected="selected">' : '>');
+          break;
+        case 'TEXTAREA':
+          tagDesc = '<textarea value="'
+              + html.escapeAttrib(node.defaultValue) + '">';
+          break;
+      }
+
+      clone = document.createElement(tagDesc);
+
+      var attrs = node.attributes;
+      for (var i = 0, attr; (attr = attrs[i]); ++i) {
+        if (attr.specified && !endsWith__.test(attr.name)) {
+          clone.setAttribute(attr.nodeName, attr.nodeValue);
+        }
+      }
+    } else {
+      clone = node.cloneNode(false);
+    }
+    if (deep) {
+      // TODO(mikesamuel): should we whitelist nodes here, to e.g. prevent
+      // untrusted code from reloading an already loaded script by cloning
+      // a script node that somehow exists in a tree accessible to it?
+      for (var child = node.firstChild; child; child = child.nextSibling) {
+        var cloneChild = constructClone(child, deep);
+        clone.appendChild(cloneChild);
+      }
+    }
+    return clone;
+  }
+
+  function fixupClone(node, clone) {
+    for (var child = node.firstChild, cloneChild = clone.firstChild;  
cloneChild;
+         child = child.nextSibling, cloneChild = cloneChild.nextSibling) {
+      fixupClone(child, cloneChild);
+    }
+    if (node.nodeType === 1) {
+      switch (node.tagName) {
+        case 'INPUT':
+          clone.value = node.value;
+          clone.checked = node.checked;
+          break;
+        case 'OPTION':
+          clone.selected = node.selected;
+          clone.value = node.value;
+          break;
+        case 'TEXTAREA':
+          clone.value = node.value;
+          break;
+      }
+    }
+
+    // Do not copy listeners since DOM2 specifies that only attributes and
+    // children are copied, and that children should only be copied if the
+    // deep flag is set.
+    // The children are handled in constructClone.
+    var originalAttribs = node.attributes___;
+    if (originalAttribs) {
+      var attribs = {};
+      clone.attributes___ = attribs;
+      cajita.forOwnKeys(originalAttribs, ___.func(function (k, v) {
+        switch (typeof v) {
+          case 'string': case 'number': case 'boolean':
+            attribs[k] = v;
+            break;
+        }
+      }));
+    }
+  }
+
    /**
     * Create a <code>style</code> element for a document containing some
     * specified CSS text. Does not add the element to the document: the  
client
@@ -137,6 +278,7 @@
    return {
      addEventListener: addEventListener,
      removeEventListener: removeEventListener,
+    cloneNode: cloneNode,
      createStylesheet: createStylesheet,
      setAttribute: setAttribute
    };

Modified: trunk/src/com/google/caja/plugin/domita.js
==============================================================================
--- trunk/src/com/google/caja/plugin/domita.js  (original)
+++ trunk/src/com/google/caja/plugin/domita.js  Fri Dec 12 16:50:24 2008
@@ -48,7 +48,7 @@
   * @requires console, document, window
   * @requires clearInterval, clearTimeout, setInterval, setTimeout
   * @requires ___, bridal, cajita, css, html, html4, unicode
- * @provides attachDocumentStub, plugin_dispatchEvent___
+ * @provides attachDocumentStub, domitaModules, plugin_dispatchEvent___
   */

  var domitaModules;
@@ -119,7 +119,7 @@
          for (var i = 0, n = activeXClassIds.length; i < n; i++) {
            var candidate = activeXClassIds[i];
            try {
-            new ActiveXObject(candidate);
+            void new ActiveXObject(candidate);
              activeXClassId = candidate;
              break;
            } catch (e) {
@@ -174,7 +174,7 @@
      // If the uriCallback rejects the URL, we throw an exception, but we  
do not
      // put the URI in the exception so as not to put the caller at risk of  
some
      // code in its stack sniffing the URI.
-    if (safeUri === undefined) { throw 'URI violates security policy'; }
+    if (safeUri === void 0) { throw 'URI violates security policy'; }
      switch (arguments.length) {
      case 2:
        this.xhr___.open(method, safeUri);
@@ -204,7 +204,7 @@
        // TODO(ihab.awad): send()-ing an empty string because send() with no
        // args does not work on FF3, others?
        this.xhr___.send('');
-    } else if (typeof opt_data == 'string') {
+    } else if (typeof opt_data === 'string') {
        this.xhr___.send(opt_data);
        return;
      } else /* if XML document */ {
@@ -691,6 +691,9 @@
                break;
            }
            break;
+        case 2:  // Attr
+          tamed = new TameAttrNode(node, editable);
+          break;
          case 3:  // Text
            tamed = new TameTextNode(node, editable);
            break;
@@ -729,10 +732,15 @@
       */
      function tameNodeList(nodeList, editable, opt_keyAttrib) {
        var tamed = [];
-      var node;
-      for (var i = nodeList.length; --i >= 0;) {
-        node = tameNode(nodeList.item(i), editable);
-        tamed[i] = node;
+      var node, untamed;
+      for (var i = 0, k = -1, n = nodeList.length; i < n; ++i) {
+        untamed = nodeList.item(i);
+        // Filter out attribute names in the protected namespace.
+        // These are created on IE as part of the association of a wrapper
+        // with the node it wraps.
+        if (untamed.nodeName && endsWith__.test(untamed.nodeName)) {  
continue; }
+        node = tameNode(untamed, editable);
+        tamed[++k] = node;
          // Make the node available via its name if doing so would not mask
          // any properties of tamed.
          var key = opt_keyAttrib && node.getAttribute(opt_keyAttrib);
@@ -744,7 +752,7 @@
            tamed[key] = node;
          }
        }
-      node = nodeList = null;
+      node = nodeList = untamed = null;

        tamed.item = ___.frozenFunc(function (k) {
          k &= 0x7fffffff;
@@ -932,8 +940,25 @@
      };
      nodeClasses.Node = TameNode;
      ___.ctor(TameNode, void 0, 'TameNode');
+    // abstract TameNode.prototype.getNodeType
+    // abstract TameNode.prototype.getNodeName
+    // abstract TameNode.prototype.getNodeValue
+    // abstract TameNode.prototype.cloneNode
+    // abstract TameNode.prototype.appendChild
+    // abstract TameNode.prototype.insertBefore
+    // abstract TameNode.prototype.removeChild
+    // abstract TameNode.prototype.replaceChild
+    // abstract TameNode.prototype.getFirstChild
+    // abstract TameNode.prototype.getLastChild
+    // abstract TameNode.prototype.getNextSibling
+    // abstract TameNode.prototype.getPreviousSibling
+    // abstract TameNode.prototype.getParentNode
+    // abstract TameNode.prototype.getElementsByTagName
+    // abstract TameNode.prototype.getElementsByClassName
+    // abstract TameNode.prototype.getChildNodes
+    // abstract TameNode.prototype.getAttributes
      var tameNodeMembers = [
-        'getNodeType', 'getNodeValue', 'getNodeName',
+        'getNodeType', 'getNodeValue', 'getNodeName', 'cloneNode',
          'appendChild', 'insertBefore', 'removeChild', 'replaceChild',
          'getFirstChild', 'getLastChild', 'getNextSibling', 
'getPreviousSibling',
          'getElementsByClassName', 'getElementsByTagName',
@@ -963,6 +988,12 @@
      TameBackedNode.prototype.getNodeValue = function () {
        return this.node___.nodeValue;
      };
+    TameBackedNode.prototype.cloneNode = function (deep) {
+      var clone = bridal.cloneNode(this.node___, Boolean(deep));
+      // From http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-3A0ED0A4
+      //     "Note that cloning an immutable subtree results in a mutable  
copy"
+      return tameNode(clone, true);
+    };
      TameBackedNode.prototype.appendChild = function (child) {
        // Child must be editable since appendChild can remove it from its  
parent.
        cajita.guard(tameNodeTrademark, child);
@@ -1246,6 +1277,10 @@
      TamePseudoElement.prototype.getTagName
          = function () { return this.tagName___; };
      TamePseudoElement.prototype.getNodeValue = function () { return null;  
};
+    TamePseudoElement.prototype.getAttribute
+        = function (attribName) { return ''; };
+    TamePseudoElement.prototype.hasAttribute
+        = function (attribName) { return false; };
      TamePseudoElement.prototype.getOwnerDocument
          = function () { return this.tameDoc___; };
      TamePseudoElement.prototype.getChildNodes
@@ -1262,7 +1297,7 @@
          // Works since html, head, body, and title can't contain  
themselves.
          return fakeNodeList([]);
        }
-      return this.getOwnerDocument().getElementsByTagName(className);
+      return this.getOwnerDocument().getElementsByTagName(tagName);
      };
      TamePseudoElement.prototype.getElementsByClassName = function  
(className) {
        return this.getOwnerDocument().getElementsByClassName(className);
@@ -1271,7 +1306,8 @@
        return '<' + this.tagName___ + '>';
      };
      ___.ctor(TamePseudoElement, TamePseudoNode, 'TamePseudoElement');
-    ___.all2(___.grantTypedGeneric, TameElement.prototype, ['getTagName']);
+    ___.all2(___.grantTypedGeneric, TameElement.prototype,
+             ['getTagName', 'getAttribute', 'hasAttribute']);


      function TameOpaqueNode(node, editable) {
@@ -1308,6 +1344,30 @@
      }
      ___.all2(___.grantTypedGeneric, TameOpaqueNode.prototype,  
tameNodeMembers);

+    function TameAttrNode(node, editable) {
+      assert(node.nodeType === 2);
+      TameBackedNode.call(this, node, editable);
+      classUtils.exportFields(
+          this, ['name', 'nodeValue', 'value', 'specified']);
+    }
+    classUtils.extend(TameAttrNode, TameBackedNode);
+    nodeClasses.Attr = TameAttrNode;
+    TameAttrNode.prototype.setNodeValue = function (value) {
+      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
+      this.node___.nodeValue = String(value || '');
+      return value;
+    };
+    TameAttrNode.prototype.getName = TameAttrNode.prototype.getNodeName;
+    TameAttrNode.prototype.getValue = TameAttrNode.prototype.getNodeValue;
+    TameAttrNode.prototype.setValue = TameAttrNode.prototype.setNodeValue;
+    TameAttrNode.prototype.getSpecified = function () {
+      return this.node___.specified;
+    };
+    TameAttrNode.prototype.toString = function () {
+      return '#attr';
+    };
+    ___.ctor(TameAttrNode, TameBackedNode, 'TameAttrNode');
+
      function TameTextNode(node, editable) {
        assert(node.nodeType === 3);
        TameBackedNode.call(this, node, editable);
@@ -1342,15 +1402,15 @@

      function getAttributeType(tagName, attribName){
        var attribKey;
-      if ((attribKey = tagName + ':' + attribName,
-          html4.ATTRIBS.hasOwnProperty(attribKey))) {
+      attribKey = tagName + ':' + attribName;
+      if (html4.ATTRIBS.hasOwnProperty(attribKey)) {
          return html4.ATTRIBS[attribKey];
        }
-      if ((attribKey = '*:' + attribName,
-          html4.ATTRIBS.hasOwnProperty(attribKey))) {
+      attribKey = '*:' + attribName;
+      if (html4.ATTRIBS.hasOwnProperty(attribKey)) {
          return html4.ATTRIBS[attribKey];
        }
-      return undefined;
+      return void 0;
      }

      function TameElement(node, editable) {
@@ -1380,7 +1440,7 @@
        attribName = String(attribName).toLowerCase();
        var tagName = this.node___.tagName.toLowerCase();
        var atype = getAttributeType(tagName, attribName);
-      if (atype === undefined) {
+      if (atype === void 0) {
          // Unrecognized attribute; use virtual map
          if (this.node___.attributes___) {
            return this.node___.attributes___[attribName] || null;
@@ -1402,6 +1462,13 @@
            }
            return null;
          default:
+          if ('' === value) {
+            // IE creates attribute nodes for any attribute in the HTML  
schema
+            // so even when they are deleted, there will be a value,  
usually
+            // the empty string.
+            var attr = this.node___.getAttributeNode(attribName);
+            if (attr && !attr.specified) { return null; }
+          }
            return value;
        }
      };
@@ -1409,13 +1476,19 @@
        attribName = String(attribName).toLowerCase();
        var tagName = this.node___.tagName.toLowerCase();
        var atype = getAttributeType(tagName, attribName);
-      if (atype === undefined) {
+      if (atype === void 0) {
          // Unrecognized attribute; use virtual map
          return !!(
              this.node___.attributes___ &&
              ___.hasOwnProp(this.node___.attributes___, attribName));
        } else {
-        return this.node___.hasAttribute(attribName);
+        var node = this.node___;
+        if (node.hasAttribute) {  // Non IE
+          return node.hasAttribute(attribName);
+        } else {
+          var attr = node.getAttributeNode(attribName);
+          return attr !== null && attr.specified;
+        }
        }
      };
      TameElement.prototype.setAttribute = function (attribName, value) {
@@ -1423,7 +1496,7 @@
        attribName = String(attribName).toLowerCase();
        var tagName = this.node___.tagName.toLowerCase();
        var atype = getAttributeType(tagName, attribName);
-      if (atype === undefined) {
+      if (atype === void 0) {
          // Unrecognized attribute; use virtual map
          if (!this.node___.attributes___) { this.node___.attributes___ =  
{}; }
          this.node___.attributes___[attribName] = String(value);
@@ -1441,7 +1514,7 @@
        attribName = String(attribName).toLowerCase();
        var tagName = this.node___.tagName.toLowerCase();
        var atype = getAttributeType(tagName, attribName);
-      if (atype === undefined) {
+      if (atype === void 0) {
          // Unrecognized attribute; use virtual map
          if (this.node___.attributes___) {
            delete this.node___.attributes___[attribName];
@@ -1641,7 +1714,7 @@
        return this.node___.reset();
      };
      TameFormElement.prototype.getAction = function () {
-      return this.getAttribute('action');
+      return this.getAttribute('action') || '';
      };
      TameFormElement.prototype.setAction = function (newVal) {
        if (!this.editable___) { throw new Error(NOT_EDITABLE); }
@@ -1688,13 +1761,13 @@
        TameElement.call(this, node, editable);
        classUtils.exportFields(
            this,
-          ['form', 'value',
-            'checked', 'disabled', 'readOnly',
-            'options', 'selected', 'selectedIndex',
-            'name', 'accessKey', 'tabIndex', 'text',
-            'defaultChecked', 'defaultSelected', 'maxLength',
-            'size', 'type', 'index', 'label',
-            'multiple', 'cols', 'rows']);
+          ['form', 'value', 'defaultValue',
+           'checked', 'disabled', 'readOnly',
+           'options', 'selected', 'selectedIndex',
+           'name', 'accessKey', 'tabIndex', 'text',
+           'defaultChecked', 'defaultSelected', 'maxLength',
+           'size', 'type', 'index', 'label',
+           'multiple', 'cols', 'rows']);
      }
      classUtils.extend(TameInputElement, TameElement);
      nodeClasses.HTMLInputElement = TameInputElement;
@@ -1706,6 +1779,8 @@
        return (this.node___.checked = !!checked);
      };
      TameInputElement.prototype.getValue = function () {
+      // For <option> elements, Firefox returns a value even when no value
+      // attribute is present, using the contained text, but IE does not.
        var value = this.node___.value;
        return value === null || value === void 0 ? null : String(value);
      };
@@ -1715,6 +1790,16 @@
            newValue === null || newValue === void 0 ? '' : '' + newValue);
        return newValue;
      };
+    TameInputElement.prototype.getDefaultValue = function () {
+      var value = this.node___.defaultValue;
+      return value === null || value === void 0 ? null : String(value);
+    };
+    TameInputElement.prototype.setDefaultValue = function (newValue) {
+      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
+      this.node___.defaultValue = (
+          newValue === null || newValue === void 0 ? '' : '' + newValue);
+      return newValue;
+    };
      TameInputElement.prototype.focus = function () {
        this.node___.focus();
      };
@@ -1727,14 +1812,6 @@
      TameInputElement.prototype.getForm = function () {
        return tameRelatedNode(this.node___.form, this.editable___);
      };
-    TameInputElement.prototype.getChecked = function () {
-      return this.node___.checked;
-    };
-    TameInputElement.prototype.setChecked = function (newValue) {
-      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
-      this.node___.checked = newValue;
-      return newValue;
-    };
      TameInputElement.prototype.getDisabled = function () {
        return this.node___.disabled;
      };
@@ -1755,7 +1832,12 @@
        return tameNodeList(this.node___.options, this.editable___, 'name');
      };
      TameInputElement.prototype.getDefaultSelected = function () {
-      return !!this.node___.defaultSelected;
+      return this.node___.defaultSelected;
+    };
+    TameInputElement.prototype.setDefaultSelected = function (newValue) {
+      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
+      this.node___.defaultSelected = !!newValue;
+      return newValue;
      };
      TameInputElement.prototype.getSelected = function () {
        return this.node___.selected;
@@ -1770,7 +1852,7 @@
      };
      TameInputElement.prototype.setSelectedIndex = function (newValue) {
        if (!this.editable___) { throw new Error(NOT_EDITABLE); }
-      this.node___.selectedIndex = newValue;
+      this.node___.selectedIndex = (newValue | 0);
        return newValue;
      };
      TameInputElement.prototype.getName = function () {
@@ -2553,7 +2635,7 @@

              var rawNode = tameElement.node___;
              if (rawNode.currentStyle && pseudoElement === void 0) {
-              return new TameComputedStyle(rawNode.currentStyle);
+              return new TameComputedStyle(rawNode.currentStyle);
              } else if (window.getComputedStyle) {
                var rawStyleNode = window.getComputedStyle(
                    tameElement.node___, pseudoElement);
@@ -2672,9 +2754,11 @@
  function plugin_dispatchEvent___(thisNode, event, pluginId, handler) {
    event = (event || window.event);
    if (typeof console !== 'undefined' && console.log) {
+    var sig = String(handler).match(/^function\b[^\)]*\)/);
      console.log(
          'Dispatch %s event thisNode=%o, event=%o, pluginId=%o, handler=%o',
-        (event && event.type), thisNode, event, pluginId, handler);
+        (event && event.type), thisNode, event, pluginId,
+        sig ? sig[0] : handler);
    }
    var imports = ___.getImports(pluginId);
    switch (typeof handler) {

Modified: trunk/tests/com/google/caja/plugin/domita_test_untrusted.html
==============================================================================
--- trunk/tests/com/google/caja/plugin/domita_test_untrusted.html       
(original)
+++ trunk/tests/com/google/caja/plugin/domita_test_untrusted.html       Fri Dec 
 
12 16:50:24 2008
@@ -176,6 +176,33 @@
    <div id="test-computed-style-invisible" class="invisible">Not here</div>
  </div>

+<div class="testcontainer" id="test-clone-node-structure">
+  <p>I have <b title="I have attributes">content</b></p>
+</div>
+
+<div class="testcontainer" id="test-clone-node-listeners">
+  <input id="test-clone-node-clickable" type="checkbox">
+</div>
+
+<div class="testcontainer" id="test-clone-node-defaults">
+  <form>
+    I should reset to the proper state.
+    <input value="default" name="text">
+    <input type="checkbox" checked name="checkbox_checked" value="on">
+    <input type="checkbox" name="checkbox_unchecked" value="on">
+    <input type="radio" name="radio" value="A">
+    <input type="radio" name="radio" checked value="B">
+    <select name="selectlist">
+      <option selected value="1">1</option>
+      <option value="2">2</option>
+    </select>
+  </form>
+</div>
+
+<p class="testcontainer" id="test-clone-node-custom-attrs">
+  I will have a custom attribute
+</p>
+
  <p class="testcontainer" id="test-document-element">Test Document  
Element</p>

  <p class="testcontainer" id="test-document-body-appendChild"
@@ -257,11 +284,21 @@
              break;
            case 'attributes':
              var attrs = node.attributes;
-            assertEquals(msg + ' #attrs', v.length, attrs.length);
+            var specified = [];
+            var names = [];
+            for (var i = 0, n = attrs.length; i < n; ++i) {
+              var attr = attrs[i];
+              if (attr.specified) {
+                specified.push(attr);
+                names.push(attr.name);
+              }
+            }
+            assertEquals(
+                msg + ' #attrs (' + names + ')', v.length,  
specified.length);
              for (var i = 0, n = v.length; i < n; ++i) {
                assertDomTree(
-                  v[i], attrs[i],
-                  stack + '@(#' + i + ':' + attrs[i].nodeName + ')');
+                  v[i], specified[i],
+                  stack + '@(#' + i + ':' + specified[i].nodeName + ')');
              }
              break;
            case 'children':
@@ -483,7 +520,7 @@
                 function testAttrsDeclaredInMarkup() {
    var d =
        document.getElementById('test-attrs-declared-in-markup').firstChild;
-
+
    assertTrue(d.hasAttribute('title'));
    assertEquals('test title', d.getAttribute('title'));
    d.setAttribute('title', 'another title');
@@ -1056,17 +1093,17 @@

  jsunitRegister('testEventHandlerAttributes',
                 function testEventHandlerAttributes() {
-  assertFalse(autoclicky.clicked[0]);
+  assertFalse('initially unclicked', autoclicky.clicked[0]);
    directAccess.click(document.getElementById('autoclicker'));
-  assertTrue(autoclicky.clicked[0]);
+  assertTrue('zero clicked', autoclicky.clicked[0]);

    var setOnclickOnMe = document.getElementById('set-onclick-on-me');
-  assertFalse(autoclicky.clicked[1]);
+  assertFalse('one not clicked', autoclicky.clicked[1]);
    directAccess.click(setOnclickOnMe);
-  assertFalse(autoclicky.clicked[1]);
+  assertFalse('one still not clicked', autoclicky.clicked[1]);
    setOnclickOnMe.onclick = function () { autoclicky.click(1); };
    directAccess.click(setOnclickOnMe);
-  assertTrue(autoclicky.clicked[1]);
+  assertTrue('one clicked', autoclicky.clicked[1]);

    pass('test-event-handler-attributes');
  });
@@ -1197,6 +1234,213 @@
    assertEquals(undefined, window.getComputedStyle(block, null).color);

    pass('test-computed-style');
+});
+
+jsunitRegister('testCloneNodeStructure', function testCloneNodeStructure()  
{
+  var p = document.getElementById('test-clone-node-structure')
+      .getElementsByTagName('P')[0];
+  assertDomTree(
+      {
+        nodeType: 1,
+        tagName: 'P',
+        attributes: [],
+        children: [ /* shallow clones contain attrs but not children. */ ]
+      },
+      p.cloneNode(false));
+  assertDomTree(
+      {
+        nodeType: 1,
+        tagName: 'P',
+        attributes: [],
+        children: [
+          {
+            nodeType: 3,
+            nodeValue: 'I have '
+          },
+          {
+            nodeType: 1,
+            nodeName: 'B',
+            attributes: [
+              {
+                nodeName: 'title',
+                nodeValue: 'I have attributes'
+              }
+            ],
+            children: [
+              {
+                nodeType: 3,
+                nodeValue: 'content'
+              }
+            ]
+          }
+        ]
+      },
+      p.cloneNode(true));
+  pass('test-clone-node-structure');
+});
+
+jsunitRegister('testCloneNodeListeners', function testCloneNodeListeners()  
{
+  var clicked = false;
+  function clickListener(event) {
+    clicked = true;
+  }
+
+  var original = document.getElementById('test-clone-node-clickable');
+
+  // Add an event to the input so we can test that event listeners are  
copied
+  // and that clone.removeEventListener modifies only clone.
+  original.addEventListener('click', clickListener);
+  directAccess.click(original);
+  assertTrue('initially clickable', clicked);
+  clicked = false;
+
+  var clone = original.cloneNode();
+  original.parentNode.insertBefore(clone, original.nextSibling);
+  // Check that listeners are not copied over.
+  directAccess.click(clone);
+  assertFalse('clone clickable', clicked);
+  clicked = false;
+
+  // Check that the original is still clickable.
+  directAccess.click(original);
+  assertTrue('original still clickable', clicked);
+  clicked = false;
+
+  pass('test-clone-node-listeners');
+});
+
+jsunitRegister('testCloneNodeDefaults', function testCloneNodeDefaults() {
+  function queryStringForForm(form, useDefaults) {
+    var parts = [];
+    var els = form.elements;
+    for (var j = 0, n = els.length; j < n; ++j) {
+      var el = els[j];
+      if (!el.name) { continue; }
+      var values = null;
+      switch (el.tagName) {
+        case 'INPUT':
+          switch (el.type.toUpperCase()) {
+            case 'CHECKBOX':
+            case 'RADIO':
+              values = (useDefaults ? el.defaultChecked : el.checked)
+                  ? [el.value] : null;
+              break;
+            default:
+              values = [useDefaults ? el.defaultValue : el.value];
+              break;
+          }
+          break;
+        case 'TEXTAREA':
+          values = [useDefaults ? el.defaultValue : el.value];
+          break;
+        case 'SELECT':
+          values = [];
+          for (var i = 0, opt; (opt = el.options[i]); ++i) {
+            if (useDefaults ? opt.defaultSelected : opt.selected) {
+              values.push(opt.value);
+            }
+          }
+          break;
+      }
+      if (values !== null) {
+        for (var i = 0; i < values.length; ++i) {
+          parts.push(encodeURIComponent(el.name) + '='
+                     + encodeURIComponent(values[i]));
+        }
+      }
+    }
+    return parts.join('&');
+  }
+
+  var form = document.getElementById('test-clone-node-defaults')
+      .getElementsByTagName('FORM')[0];
+  assertEquals(
+      'initial form state',
+      'text=default&checkbox_checked=on&radio=B&selectlist=1',
+      queryStringForForm(form));
+
+  // Change the values on the original
+  form.elements.text.value = 'changed';
+  form.elements.checkbox_checked.checked = false;
+  form.elements.checkbox_unchecked.checked = true;
+  form.elements[3].checked = true;
+  form.elements.selectlist.options[1].selected = true;
+  assertEquals(
+      'changed form state',
+      'text=changed&checkbox_unchecked=on&radio=A&selectlist=2',
+      queryStringForForm(form));
+
+  // Check the values in the clone
+  var clone = form.cloneNode(true);
+  // Add the clone to the DOM, or reset() below will have no effect on it
+  // on Firefox.  Heisenbug.
+  form.parentNode.insertBefore(clone, form);
+  // HACK(mikesamuel): IE6&7 fail to update the checked state for radio  
buttons,
+  // and IE 6 fails to updated the checked state for checkboxes until the  
form
+  // containing it is part of the DOM.
+  if (!','.split(new RegExp(',')).length) {
+    clone.elements[3].checked = true;
+    clone.elements.checkbox_unchecked.checked = true;
+    clone.elements.checkbox_checked.checked = false;
+  }
+  assertEquals(
+      'clone state',
+      'text=changed&checkbox_unchecked=on&radio=A&selectlist=2',
+      queryStringForForm(clone));
+  assertEquals(
+      'clone defaults',
+      'text=default&checkbox_checked=on&radio=B&selectlist=1',
+      queryStringForForm(clone, true));
+
+  // Reset both and check the values on each
+  clone.reset();
+  assertEquals(
+      'form state post clone reset',
+      'text=changed&checkbox_unchecked=on&radio=A&selectlist=2',
+      queryStringForForm(form));
+  assertEquals(
+      'clone state post reset',
+      'text=default&checkbox_checked=on&radio=B&selectlist=1',
+      queryStringForForm(clone));
+  form.reset();
+  assertEquals(
+      'clone state post form reset',
+      'text=default&checkbox_checked=on&radio=B&selectlist=1',
+      queryStringForForm(clone));
+  assertEquals(
+      'form state post reset',
+      'text=default&checkbox_checked=on&radio=B&selectlist=1',
+      queryStringForForm(form));
+
+  pass('test-clone-node-defaults');
+});
+
+jsunitRegister('testCloneNodeCustomAttrs', function  
testCloneNodeCustomAttrs() {
+  var node = document.getElementById('test-clone-node-custom-attrs');
+  node.setAttribute('bogus', 'foo');
+
+  var clone = node.cloneNode(true);
+  assertEquals('clone value', 'foo', clone.getAttribute('bogus'));
+  assertTrue('clone has attr', clone.hasAttribute('bogus'));
+  assertTrue('original has attr', node.hasAttribute('bogus'));
+
+  clone.setAttribute('bogus', 'bar');
+  assertEquals('clone changed', 'bar', clone.getAttribute('bogus'));
+  assertEquals('original unchanged', 'foo', node.getAttribute('bogus'));
+
+  clone.removeAttribute('bogus');
+  assertEquals('clone deleted', null, clone.getAttribute('bogus'));
+  assertFalse('deleted things do not exist', clone.hasAttribute('bogus'));
+  assertEquals('original not deleted', 'foo', node.getAttribute('bogus'));
+  assertTrue('original attr exists', node.hasAttribute('bogus'));
+
+  node.setAttribute('bogus', 'boo');
+  assertEquals('clone still deleted', null, clone.getAttribute('bogus'));
+  assertFalse('deleted things still do not exist',  
clone.hasAttribute('bogus'));
+  assertEquals('original changed', 'boo', node.getAttribute('bogus'));
+  assertTrue('original attr still exists', node.hasAttribute('bogus'));
+
+  pass('test-clone-node-custom-attrs');
  });

  jsunitRegister('testDocumentElement',

Modified: trunk/tests/com/google/caja/plugin/jsunit.js
==============================================================================
--- trunk/tests/com/google/caja/plugin/jsunit.js        (original)
+++ trunk/tests/com/google/caja/plugin/jsunit.js        Fri Dec 12 16:50:24 2008
@@ -97,11 +97,36 @@
        return resultsNode;
      }

+    function escapeAttrib(s) {
+      return s.replace(/&/g, '&amp;').replace(/\"/g, '&quot;')
+          .replace(/</g, '&lt;').replace(/>/g, '&gt;');
+    }
+
+    var htmlBuf = null;
      function emitElement(elName, text, className) {
-      var el = document.createElement(elName);
-      el.appendChild(document.createTextNode(text));
-      if (className) { el.className = className; }
-      getResultsNode().appendChild(el);
+      if (typeof setTimeout !== 'undefined') {
+        if (!htmlBuf) {
+          htmlBuf = [];
+          setTimeout(
+              function () {
+                var div = document.createElement('DIV');
+                div.innerHTML = htmlBuf.join('');
+                getResultsNode().appendChild(div);
+                htmlBuf = null;
+              },
+              0);
+        }
+        htmlBuf.push(
+            '<' + elName
+            + (className ? ' class="' + escapeAttrib(className)  
+ '">' : '>')
+            + escapeAttrib(text)
+            + '</' + elName + '>');
+      } else {
+        var el = document.createElement(elName);
+        el.appendChild(document.createTextNode(text));
+        if (className) { el.className = className; }
+        getResultsNode().appendChild(el);
+      }
      }

      function toMessage(args) {

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to 
http://groups.google.com/group/google-caja-discuss
To unsubscribe, email [email protected]
-~----------~----~----~----~------~----~------~--~---

Reply via email to