Add document.defineCustomElement
authorrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 15 Jan 2016 02:59:03 +0000 (02:59 +0000)
committerrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 15 Jan 2016 02:59:03 +0000 (02:59 +0000)
https://bugs.webkit.org/show_bug.cgi?id=153092

Reviewed by Chris Dumez.

Source/WebCore:

Added document.defineCustomElement and added a constructor to HTMLElement which can be called
as "super" in a subclass of HTMLElement. This is a prototype of new custom elements API and
willfully violates the current specification at http://w3c.github.io/webcomponents/spec/custom/

Each author defined class can define multiple elements using distinct tag names. In such cases,
the super call must specify the tag name. e.g.

class SomeCustomElement extends HTMLElement { constructor(name) { super(name); } }
document.defineCustomElement('some-custom-element', SomeCustomElement);
document.defineCustomElement('other-custom-element', SomeCustomElement);
new SomeCustomElement('some-custom-element');

When a class is associated with exactly one tag name, the argument can be omitted. e.g.

class AnotherCustomElement extends HTMLElement {}
document.defineCustomElement('another-custom-element', AnotherCustomElement);
new AnotherCustomElement();

We allow only subclassing of HTMLElement and only in (X)HTML namespace.

Tests: fast/custom-elements/Document-defineCustomElement.html
       fast/custom-elements/HTMLElement-constructor.html

* CMakeLists.txt:
* WebCore.xcodeproj/project.pbxproj:

* bindings/js/JSCustomElementInterface.cpp: Added. Abstracts an author-defined class associated
with a custom element. It's a Active DOM object and lives until the associated document dies.
(WebCore::JSCustomElementInterface::JSCustomElementInterface):
(WebCore::JSCustomElementInterface::~JSCustomElementInterface):
* bindings/js/JSCustomElementInterface.h: Added.
(WebCore::JSCustomElementInterface::create):
(WebCore::JSCustomElementInterface::scriptExecutionContext):
(WebCore::JSCustomElementInterface::constructor):

* bindings/js/JSDocumentCustom.cpp:
(WebCore::JSDocument::defineCustomElement): Added. Define a custom element by associating a tag
name with an author defined JS class after validating arguments.

* bindings/js/JSHTMLElementCustom.cpp:
(WebCore::constructJSHTMLElement): Added. Look up the tag name based on new.target if one is not
specified. If a tag name is specified, check that new.target is associated with the tag name.

* dom/CustomElementDefinitions.cpp: Added.
(WebCore::CustomElementDefinitions::checkName): Added. Restricts tag names similarly to
http://w3c.github.io/webcomponents/spec/custom/#dfn-custom-element-type
(WebCore::CustomElementDefinitions::defineElement): Added. Associates a JS class with a tag name.
(WebCore::CustomElementDefinitions::findInterface): Added. Finds a JS class by a tag name.
(WebCore::CustomElementDefinitions::findName): Added. Finds a tag name by a JS class.
* dom/CustomElementDefinitions.h: Added.
(WebCore::CustomElementDefinitions::CustomElementInfo): Added.

* dom/Document.cpp:
(WebCore::Document::ensureCustomElementDefinitions): Added.
* dom/Document.h:
(WebCore::Document::customElementDefinitions): Added.

* dom/Document.idl:
* html/HTMLElement.idl:

LayoutTests:

Added tests for document.defineCustomElement and instantiating custom elements.

* TestExpectations: Skipped the tests on non-Mac ports.
* fast/custom-elements: Added.
* fast/custom-elements/Document-defineCustomElement-expected.txt: Added.
* fast/custom-elements/Document-defineCustomElement.html: Added.
* fast/custom-elements/HTMLElement-constructor-expected.txt: Added.
* fast/custom-elements/HTMLElement-constructor.html: Added.
* platform/mac/TestExpectations:

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@195087 268f45cc-cd09-0410-ab3c-d52691b4dbfc

20 files changed:
LayoutTests/ChangeLog
LayoutTests/TestExpectations
LayoutTests/fast/custom-elements/Document-defineCustomElement-expected.txt [new file with mode: 0644]
LayoutTests/fast/custom-elements/Document-defineCustomElement.html [new file with mode: 0644]
LayoutTests/fast/custom-elements/HTMLElement-constructor-expected.txt [new file with mode: 0644]
LayoutTests/fast/custom-elements/HTMLElement-constructor.html [new file with mode: 0644]
LayoutTests/platform/mac/TestExpectations
Source/WebCore/CMakeLists.txt
Source/WebCore/ChangeLog
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/bindings/js/JSCustomElementInterface.cpp [new file with mode: 0644]
Source/WebCore/bindings/js/JSCustomElementInterface.h [new file with mode: 0644]
Source/WebCore/bindings/js/JSDocumentCustom.cpp
Source/WebCore/bindings/js/JSHTMLElementCustom.cpp
Source/WebCore/dom/CustomElementDefinitions.cpp [new file with mode: 0644]
Source/WebCore/dom/CustomElementDefinitions.h [new file with mode: 0644]
Source/WebCore/dom/Document.cpp
Source/WebCore/dom/Document.h
Source/WebCore/dom/Document.idl
Source/WebCore/html/HTMLElement.idl

index 0010778..6728ae0 100644 (file)
@@ -1,3 +1,20 @@
+2016-01-14  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Add document.defineCustomElement
+        https://bugs.webkit.org/show_bug.cgi?id=153092
+
+        Reviewed by Chris Dumez.
+
+        Added tests for document.defineCustomElement and instantiating custom elements.
+
+        * TestExpectations: Skipped the tests on non-Mac ports.
+        * fast/custom-elements: Added.
+        * fast/custom-elements/Document-defineCustomElement-expected.txt: Added.
+        * fast/custom-elements/Document-defineCustomElement.html: Added.
+        * fast/custom-elements/HTMLElement-constructor-expected.txt: Added.
+        * fast/custom-elements/HTMLElement-constructor.html: Added.
+        * platform/mac/TestExpectations:
+
 2016-01-14  Beth Dakin  <bdakin@apple.com>
 
         WK2: Request completion candidates when needed
index 1cefc0a..ad09d45 100644 (file)
@@ -740,6 +740,7 @@ webkit.org/b/148884 imported/w3c/web-platform-tests/html/semantics/forms/textfie
 webkit.org/b/148922 svg/as-object/svg-in-object-dynamic-attribute-change.html [ Pass ImageOnlyFailure ]
 webkit.org/b/148925 svg/dom/svg-root-lengths.html [ Pass Failure ]
 
+webkit.org/b/150225 fast/custom-elements [ Failure ]
 webkit.org/b/148695 fast/shadow-dom [ Failure ImageOnlyFailure ]
 
 # Known failures on CSS Variables Test Suite
diff --git a/LayoutTests/fast/custom-elements/Document-defineCustomElement-expected.txt b/LayoutTests/fast/custom-elements/Document-defineCustomElement-expected.txt
new file mode 100644 (file)
index 0000000..56e94be
--- /dev/null
@@ -0,0 +1,7 @@
+
+PASS Check the existence of defineCustomElement on Document interface 
+PASS document.defineCustomElement should throw with an invalid name 
+PASS document.defineCustomElement should throw with a duplicate name 
+PASS document.defineCustomElement should throw when the element interface is not a constructor 
+PASS document.defineCustomElement should define an instantiatable custom element 
+
diff --git a/LayoutTests/fast/custom-elements/Document-defineCustomElement.html b/LayoutTests/fast/custom-elements/Document-defineCustomElement.html
new file mode 100644 (file)
index 0000000..e53f1b2
--- /dev/null
@@ -0,0 +1,92 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Custom Elements: Extensions to Document interface</title>
+<meta name="author" title="Ryosuke Niwa" href="mailto:rniwa@webkit.org">
+<meta name="assert" content="document.defineCustomElement should define a custom element">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<link rel='stylesheet' href='../../resources/testharness.css'>
+</head>
+<body>
+<div id="log"></div>
+<script>
+
+test(function () {
+    assert_true('defineCustomElement' in Document.prototype, '"defineCustomElement" exists on Document.prototype');
+    assert_true('defineCustomElement' in document, '"defineCustomElement" exists on document');
+}, 'Check the existence of defineCustomElement on Document interface');
+
+test(function () {
+    class MyCustomElement extends HTMLElement {};
+
+    assert_throws({'name': 'SyntaxError'}, function () { document.defineCustomElement(null, MyCustomElement); },
+        'document.defineCustomElement must throw a SyntaxError if the tag name is null');
+    assert_throws({'name': 'SyntaxError'}, function () { document.defineCustomElement('', MyCustomElement); },
+        'document.defineCustomElement must throw a SyntaxError if the tag name is empty');
+    assert_throws({'name': 'SyntaxError'}, function () { document.defineCustomElement('abc', MyCustomElement); },
+        'document.defineCustomElement must throw a SyntaxError if the tag name does not contain "-"');
+    assert_throws({'name': 'SyntaxError'}, function () { document.defineCustomElement('a-Bc', MyCustomElement); },
+        'document.defineCustomElement must throw a SyntaxError if the tag name contains an upper case letter');
+
+    var builtinTagNames = [
+        'annotation-xml',
+        'color-profile',
+        'font-face',
+        'font-face-src',
+        'font-face-uri',
+        'font-face-format',
+        'font-face-name',
+        'missing-glyph'
+    ];
+
+    for (var tagName of builtinTagNames) {
+        assert_throws({'name': 'SyntaxError'}, function () { document.defineCustomElement(tagName, MyCustomElement); },
+            'document.defineCustomElement must throw a SyntaxError if the tag name is "' + tagName + '"');
+    }
+
+}, 'document.defineCustomElement should throw with an invalid name');
+
+test(function () {
+    class SomeCustomElement extends HTMLElement {};
+    class OtherCustomElement extends HTMLElement {};
+
+    document.defineCustomElement('some-custom-element', SomeCustomElement);
+    assert_throws({'name': 'NotSupportedError'}, function () { document.defineCustomElement('some-custom-element', OtherCustomElement); },
+        'document.defineCustomElement must throw a NotSupportedError if the specified tag name is already used');
+
+}, 'document.defineCustomElement should throw with a duplicate name');
+
+test(function () {
+    assert_throws({'name': 'TypeError'}, function () { document.defineCustomElement('invalid-element', 1); },
+        'document.defineCustomElement must throw a TypeError when the element interface is a number');
+    assert_throws({'name': 'TypeError'}, function () { document.defineCustomElement('invalid-element', '123'); },
+        'document.defineCustomElement must throw a TypeError when the element interface is a string');
+    assert_throws({'name': 'TypeError'}, function () { document.defineCustomElement('invalid-element', {}); },
+        'document.defineCustomElement must throw a TypeError when the element interface is an object');
+    assert_throws({'name': 'TypeError'}, function () { document.defineCustomElement('invalid-element', []); },
+        'document.defineCustomElement must throw a TypeError when the element interface is an array');
+}, 'document.defineCustomElement should throw when the element interface is not a constructor');
+
+test(function () {
+    class MyCustomElement extends HTMLElement {};
+    document.defineCustomElement('my-custom-element', MyCustomElement);
+
+    var instance = new MyCustomElement;
+    assert_true(instance instanceof MyCustomElement,
+        'An instance of a custom HTML element be an instance of the associated interface');
+
+    assert_true(instance instanceof HTMLElement,
+        'An instance of a custom HTML element must inherit from HTMLElement');
+
+    assert_equals(instance.localName, 'my-custom-element',
+        'An instance of a custom element must use the associated tag name');
+
+    assert_equals(instance.namespaceURI, 'http://www.w3.org/1999/xhtml',
+        'A custom element HTML must use HTML namespace');
+
+}, 'document.defineCustomElement should define an instantiatable custom element');
+
+</script>
+</body>
+</html>
diff --git a/LayoutTests/fast/custom-elements/HTMLElement-constructor-expected.txt b/LayoutTests/fast/custom-elements/HTMLElement-constructor-expected.txt
new file mode 100644 (file)
index 0000000..628b5a3
--- /dev/null
@@ -0,0 +1,8 @@
+
+PASS HTMLElement constructor must throw a TypeError when there is no derived class 
+PASS HTMLElement constructor must throw TypeError when custom element is not well defined 
+PASS HTMLElement constructor must infer the tag name from the element interface 
+PASS HTMLElement constructor must allow associating an element interface with multiple tag names 
+PASS HTMLElement constructor must allow subclassing a custom element 
+PASS HTMLElement constructor must allow subclassing an user-defined subclass of HTMLElement 
+
diff --git a/LayoutTests/fast/custom-elements/HTMLElement-constructor.html b/LayoutTests/fast/custom-elements/HTMLElement-constructor.html
new file mode 100644 (file)
index 0000000..5d5d3a5
--- /dev/null
@@ -0,0 +1,108 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Custom Elements: HTMLElement must allow subclassing</title>
+<meta name="author" title="Ryosuke Niwa" href="mailto:rniwa@webkit.org">
+<meta name="assert" content="HTMLElement must allow subclassing">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<link rel='stylesheet' href='../../resources/testharness.css'>
+</head>
+<body>
+<div id="log"></div>
+<script>
+
+test(function () {
+    class SomeDefinedElement extends HTMLElement {};
+    document.defineCustomElement('defined-element', SomeDefinedElement);
+    assert_throws({'name': 'TypeError'}, function () { new HTMLElement('defined-element'); });
+}, 'HTMLElement constructor must throw a TypeError when there is no derived class');
+
+test(function () {
+    class SomeCustomElement extends HTMLElement {};
+    assert_throws({'name': 'TypeError'}, function () { new SomeCustomElement; },
+        'Instantiating a custom element without calling defineCustomElement must throw TypeError');
+
+    class AnotherCustomElement extends HTMLElement {
+        constructor() { super('some-element'); }
+    };
+    document.defineCustomElement('another-element', AnotherCustomElement);
+    assert_throws({'name': 'TypeError'}, function () { new AnotherCustomElement; },
+        'Calling HTMLElement constructor with a mismatching tag name throw TypeError');
+
+    class YetAnotherCustomElement extends HTMLElement {
+        constructor() { super(1); }
+    };
+    document.defineCustomElement('yet-another-element', YetAnotherCustomElement);
+    assert_throws({'name': 'TypeError'}, function () { new YetAnotherCustomElement; },
+        'Calling HTMLElement constructor with a bad tag name throw TypeError');
+
+}, 'HTMLElement constructor must throw TypeError when custom element is not well defined');
+
+test(function () {
+    class CustomElementWithInferredTagName extends HTMLElement {};
+    document.defineCustomElement('inferred-name', CustomElementWithInferredTagName);
+
+    var instance = new CustomElementWithInferredTagName;
+    assert_true(instance instanceof Element, 'A custom element must inherit from Element');
+    assert_true(instance instanceof Node, 'A custom element must inherit from Node');
+    assert_equals(instance.localName, 'inferred-name');
+    assert_equals(instance.nodeName, 'INFERRED-NAME');
+    assert_equals(instance.namespaceURI, 'http://www.w3.org/1999/xhtml', 'A custom HTML element must use HTML namespace');
+
+    document.body.appendChild(instance);
+    assert_equals(document.body.lastChild, instance,
+        'document.body.appendChild must be able to insert a custom element');
+    assert_equals(document.querySelector('inferred-name'), instance,
+        'document.querySelector must be able to find a custom element by its tag name');
+
+}, 'HTMLElement constructor must infer the tag name from the element interface');
+
+test(function () {
+    class ElementWithMultipleTagNames extends HTMLElement { };
+    document.defineCustomElement('custom-element-1', ElementWithMultipleTagNames);
+    document.defineCustomElement('custom-element-2', ElementWithMultipleTagNames);
+
+    var instance1 = new ElementWithMultipleTagNames('custom-element-1');
+    assert_true(instance1 instanceof ElementWithMultipleTagNames);
+    assert_equals(instance1.localName, 'custom-element-1');
+    assert_equals(instance1.nodeName, 'CUSTOM-ELEMENT-1');
+
+    var instance2 = new ElementWithMultipleTagNames('custom-element-2');
+    assert_true(instance2 instanceof ElementWithMultipleTagNames);
+    assert_equals(instance2.localName, 'custom-element-2');
+    assert_equals(instance2.nodeName, 'CUSTOM-ELEMENT-2');
+
+    assert_throws({'name': 'TypeError'}, function () { new ElementWithMultipleTagNames; },
+        'Instantiating an element interface associated with multiple tag names without specifying the tag name must throw TypeError');
+
+}, 'HTMLElement constructor must allow associating an element interface with multiple tag names');
+
+test(function () {
+    class ConcreteCustomElement extends HTMLElement { };
+    class SubCustomElement extends ConcreteCustomElement { };
+    document.defineCustomElement('concrete-custom-element', ConcreteCustomElement);
+    document.defineCustomElement('sub-custom-element', SubCustomElement);
+
+    var instance = new SubCustomElement();
+    assert_true(instance instanceof SubCustomElement);
+    assert_equals(instance.localName, 'sub-custom-element');
+    assert_equals(instance.nodeName, 'SUB-CUSTOM-ELEMENT');
+
+}, 'HTMLElement constructor must allow subclassing a custom element');
+
+test(function () {
+    class AbstractCustomElement extends HTMLElement { };
+    class ConcreteSubCustomElement extends AbstractCustomElement { };
+    document.defineCustomElement('concrete-sub-custom-element', ConcreteSubCustomElement);
+
+    var instance = new ConcreteSubCustomElement();
+    assert_true(instance instanceof ConcreteSubCustomElement);
+    assert_equals(instance.localName, 'concrete-sub-custom-element');
+    assert_equals(instance.nodeName, 'CONCRETE-SUB-CUSTOM-ELEMENT');
+
+}, 'HTMLElement constructor must allow subclassing an user-defined subclass of HTMLElement');
+
+</script>
+</body>
+</html>
index 632f230..edfb9a3 100644 (file)
@@ -1258,6 +1258,8 @@ webkit.org/b/149440 fast/shadow-dom/css-scoping-shadow-host-functional-rule.html
 webkit.org/b/149441 fast/shadow-dom/css-scoping-shadow-slotted-rule.html [ ImageOnlyFailure ]
 webkit.org/b/149441 fast/shadow-dom/css-scoping-shadow-slot-display-override.html [ ImageOnlyFailure ]
 
+webkit.org/b/150225 fast/custom-elements [ Pass ]
+
 # Times out in debug.
 [ Debug ] js/regress/getter-richards-try-catch.html [ Skip ]
 
index 26304f6..bebb279 100644 (file)
@@ -1114,6 +1114,7 @@ set(WebCore_SOURCES
     bindings/js/JSCryptoKeyPairCustom.cpp
     bindings/js/JSCryptoKeySerializationJWK.cpp
     bindings/js/JSCryptoOperationData.cpp
+    bindings/js/JSCustomElementInterface.cpp
     bindings/js/JSCustomEventCustom.cpp
     bindings/js/JSCustomSQLStatementErrorCallback.cpp
     bindings/js/JSCustomXPathNSResolver.cpp
@@ -1407,6 +1408,7 @@ set(WebCore_SOURCES
     dom/ContainerNode.cpp
     dom/ContainerNodeAlgorithms.cpp
     dom/ContextDestructionObserver.cpp
+    dom/CustomElementDefinitions.cpp
     dom/CustomEvent.cpp
     dom/DOMCoreException.cpp
     dom/DOMError.cpp
index b36f405..270eed7 100644 (file)
@@ -1,3 +1,70 @@
+2016-01-14  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Add document.defineCustomElement
+        https://bugs.webkit.org/show_bug.cgi?id=153092
+
+        Reviewed by Chris Dumez.
+
+        Added document.defineCustomElement and added a constructor to HTMLElement which can be called
+        as "super" in a subclass of HTMLElement. This is a prototype of new custom elements API and
+        willfully violates the current specification at http://w3c.github.io/webcomponents/spec/custom/
+
+        Each author defined class can define multiple elements using distinct tag names. In such cases,
+        the super call must specify the tag name. e.g.
+
+        class SomeCustomElement extends HTMLElement { constructor(name) { super(name); } }
+        document.defineCustomElement('some-custom-element', SomeCustomElement);
+        document.defineCustomElement('other-custom-element', SomeCustomElement);
+        new SomeCustomElement('some-custom-element');
+
+        When a class is associated with exactly one tag name, the argument can be omitted. e.g.
+
+        class AnotherCustomElement extends HTMLElement {}
+        document.defineCustomElement('another-custom-element', AnotherCustomElement);
+        new AnotherCustomElement();
+
+        We allow only subclassing of HTMLElement and only in (X)HTML namespace.
+
+        Tests: fast/custom-elements/Document-defineCustomElement.html
+               fast/custom-elements/HTMLElement-constructor.html
+
+        * CMakeLists.txt:
+        * WebCore.xcodeproj/project.pbxproj:
+
+        * bindings/js/JSCustomElementInterface.cpp: Added. Abstracts an author-defined class associated
+        with a custom element. It's a Active DOM object and lives until the associated document dies.
+        (WebCore::JSCustomElementInterface::JSCustomElementInterface):
+        (WebCore::JSCustomElementInterface::~JSCustomElementInterface):
+        * bindings/js/JSCustomElementInterface.h: Added.
+        (WebCore::JSCustomElementInterface::create):
+        (WebCore::JSCustomElementInterface::scriptExecutionContext):
+        (WebCore::JSCustomElementInterface::constructor):
+
+        * bindings/js/JSDocumentCustom.cpp:
+        (WebCore::JSDocument::defineCustomElement): Added. Define a custom element by associating a tag
+        name with an author defined JS class after validating arguments.
+
+        * bindings/js/JSHTMLElementCustom.cpp:
+        (WebCore::constructJSHTMLElement): Added. Look up the tag name based on new.target if one is not
+        specified. If a tag name is specified, check that new.target is associated with the tag name.
+
+        * dom/CustomElementDefinitions.cpp: Added.
+        (WebCore::CustomElementDefinitions::checkName): Added. Restricts tag names similarly to
+        http://w3c.github.io/webcomponents/spec/custom/#dfn-custom-element-type
+        (WebCore::CustomElementDefinitions::defineElement): Added. Associates a JS class with a tag name.
+        (WebCore::CustomElementDefinitions::findInterface): Added. Finds a JS class by a tag name.
+        (WebCore::CustomElementDefinitions::findName): Added. Finds a tag name by a JS class.
+        * dom/CustomElementDefinitions.h: Added.
+        (WebCore::CustomElementDefinitions::CustomElementInfo): Added.
+
+        * dom/Document.cpp:
+        (WebCore::Document::ensureCustomElementDefinitions): Added.
+        * dom/Document.h:
+        (WebCore::Document::customElementDefinitions): Added.
+
+        * dom/Document.idl:
+        * html/HTMLElement.idl:
+
 2016-01-14  Simon Fraser  <simon.fraser@apple.com>
 
         Remove workaround for rdar://problem/23623670
index 9c1f915..09eb498 100644 (file)
                9BC6C21C13CCC97B008E0337 /* HTMLTextFormControlElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BC6C21A13CCC97B008E0337 /* HTMLTextFormControlElement.cpp */; };
                9BD0BF9312A42BF50072FD43 /* ScopedEventQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BD0BF9112A42BF50072FD43 /* ScopedEventQueue.h */; };
                9BD0BF9412A42BF50072FD43 /* ScopedEventQueue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BD0BF9212A42BF50072FD43 /* ScopedEventQueue.cpp */; };
+               9BD4E9161C462872005065BC /* JSCustomElementInterface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BD4E9141C462872005065BC /* JSCustomElementInterface.cpp */; };
+               9BD4E9171C462872005065BC /* JSCustomElementInterface.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BD4E9151C462872005065BC /* JSCustomElementInterface.h */; };
+               9BD4E91A1C462CFC005065BC /* CustomElementDefinitions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BD4E9181C462CFC005065BC /* CustomElementDefinitions.cpp */; };
+               9BD4E91B1C462CFC005065BC /* CustomElementDefinitions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BD4E9191C462CFC005065BC /* CustomElementDefinitions.h */; };
                9BD8A95A18BEFC7600987E9A /* CollectionIndexCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9BD8A95918BEFC7600987E9A /* CollectionIndexCache.cpp */; };
                9BDA64D71B975CE5009C4387 /* JSShadowRoot.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B6BC9601B975966005AE1F0 /* JSShadowRoot.cpp */; };
                9BDA64D81B975CF2009C4387 /* JSShadowRoot.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B6BC9611B975966005AE1F0 /* JSShadowRoot.h */; };
                9BC6C21A13CCC97B008E0337 /* HTMLTextFormControlElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HTMLTextFormControlElement.cpp; sourceTree = "<group>"; };
                9BD0BF9112A42BF50072FD43 /* ScopedEventQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScopedEventQueue.h; sourceTree = "<group>"; };
                9BD0BF9212A42BF50072FD43 /* ScopedEventQueue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScopedEventQueue.cpp; sourceTree = "<group>"; };
+               9BD4E9141C462872005065BC /* JSCustomElementInterface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSCustomElementInterface.cpp; sourceTree = "<group>"; };
+               9BD4E9151C462872005065BC /* JSCustomElementInterface.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSCustomElementInterface.h; sourceTree = "<group>"; };
+               9BD4E9181C462CFC005065BC /* CustomElementDefinitions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CustomElementDefinitions.cpp; sourceTree = "<group>"; };
+               9BD4E9191C462CFC005065BC /* CustomElementDefinitions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CustomElementDefinitions.h; sourceTree = "<group>"; };
                9BD8A95918BEFC7600987E9A /* CollectionIndexCache.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CollectionIndexCache.cpp; sourceTree = "<group>"; };
                9BF9A87E1648DD2F001C6B23 /* JSHTMLFormControlsCollection.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSHTMLFormControlsCollection.cpp; sourceTree = "<group>"; };
                9BF9A87F1648DD2F001C6B23 /* JSHTMLFormControlsCollection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSHTMLFormControlsCollection.h; sourceTree = "<group>"; };
                                1432E8460C51493800B1500F /* GCController.h */,
                                C585A66011D4FAC5004C3E4B /* IDBBindingUtilities.cpp */,
                                C585A66111D4FAC5004C3E4B /* IDBBindingUtilities.h */,
+                               9BD4E9141C462872005065BC /* JSCustomElementInterface.cpp */,
+                               9BD4E9151C462872005065BC /* JSCustomElementInterface.h */,
                                E157A8EE18185425009F821D /* JSCryptoAlgorithmBuilder.cpp */,
                                E157A8EF18185425009F821D /* JSCryptoAlgorithmBuilder.h */,
                                E1C657101815F9DD00256CDD /* JSCryptoAlgorithmDictionary.cpp */,
                                E1A1470711102B1500EEC0F3 /* ContainerNodeAlgorithms.h */,
                                97627B8B14FB3CEE002CDCA1 /* ContextDestructionObserver.cpp */,
                                97627B8C14FB3CEE002CDCA1 /* ContextDestructionObserver.h */,
+                               9BD4E9181C462CFC005065BC /* CustomElementDefinitions.cpp */,
+                               9BD4E9191C462CFC005065BC /* CustomElementDefinitions.h */,
                                62CD32561157E57C0063B0A7 /* CustomEvent.cpp */,
                                62CD32571157E57C0063B0A7 /* CustomEvent.h */,
                                62CD32581157E57C0063B0A7 /* CustomEvent.idl */,
                                85ECBEEB0AA7626900544F0B /* DOMHTMLAreaElement.h in Headers */,
                                85E7119C0AC5D5350053270F /* DOMHTMLAreaElementInternal.h in Headers */,
                                859A9C470AA5E3BD00B694B2 /* DOMHTMLBaseElement.h in Headers */,
+                               9BD4E9171C462872005065BC /* JSCustomElementInterface.h in Headers */,
                                85E7119D0AC5D5350053270F /* DOMHTMLBaseElementInternal.h in Headers */,
                                85ECBEED0AA7626900544F0B /* DOMHTMLBaseFontElement.h in Headers */,
                                85E7119E0AC5D5350053270F /* DOMHTMLBaseFontElementInternal.h in Headers */,
                                B2FA3D6F0AB75A6F000E5AC4 /* JSSVGFEComponentTransferElement.h in Headers */,
                                B2FA3D710AB75A6F000E5AC4 /* JSSVGFECompositeElement.h in Headers */,
                                19BFF64F11C0F2AC00B8C04D /* JSSVGFEConvolveMatrixElement.h in Headers */,
+                               9BD4E91B1C462CFC005065BC /* CustomElementDefinitions.h in Headers */,
                                B2FA3D730AB75A6F000E5AC4 /* JSSVGFEDiffuseLightingElement.h in Headers */,
                                B2FA3D750AB75A6F000E5AC4 /* JSSVGFEDisplacementMapElement.h in Headers */,
                                B2FA3D770AB75A6F000E5AC4 /* JSSVGFEDistantLightElement.h in Headers */,
                                51DCE8020CAC9F1C00488358 /* JSSQLResultSetRowListCustom.cpp in Sources */,
                                B59DD6A611902A62007E9684 /* JSSQLStatementCallback.cpp in Sources */,
                                B59DD6AA11902A71007E9684 /* JSSQLStatementErrorCallback.cpp in Sources */,
+                               9BD4E9161C462872005065BC /* JSCustomElementInterface.cpp in Sources */,
                                514C76380CE9225E007EF3CD /* JSSQLTransaction.cpp in Sources */,
                                B59DD69E11902A42007E9684 /* JSSQLTransactionCallback.cpp in Sources */,
                                1AD2316E0CD269E700C1F194 /* JSSQLTransactionCustom.cpp in Sources */,
                                A8DF4AE80980C42C0052981B /* RenderTableCol.cpp in Sources */,
                                A8DF4AF00980C42C0052981B /* RenderTableRow.cpp in Sources */,
                                A8DF4AED0980C42C0052981B /* RenderTableSection.cpp in Sources */,
+                               9BD4E91A1C462CFC005065BC /* CustomElementDefinitions.cpp in Sources */,
                                BCEA488B097D93020094C9E4 /* RenderText.cpp in Sources */,
                                AB67D1A8097F3AE300F9392E /* RenderTextControl.cpp in Sources */,
                                083DAEA60F01A7FB00342754 /* RenderTextControlMultiLine.cpp in Sources */,
diff --git a/Source/WebCore/bindings/js/JSCustomElementInterface.cpp b/Source/WebCore/bindings/js/JSCustomElementInterface.cpp
new file mode 100644 (file)
index 0000000..dcef342
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "JSCustomElementInterface.h"
+
+#if ENABLE(CUSTOM_ELEMENTS)
+
+#include "DOMWrapperWorld.h"
+#include "Element.h"
+#include "JSDOMGlobalObject.h"
+#include "JSElement.h"
+#include "JSMainThreadExecState.h"
+#include "JSMainThreadExecStateInstrumentation.h"
+#include "ScriptExecutionContext.h"
+#include <heap/WeakInlines.h>
+#include <runtime/JSLock.h>
+
+using namespace JSC;
+
+namespace WebCore {
+
+JSCustomElementInterface::JSCustomElementInterface(JSObject* constructor, JSDOMGlobalObject* globalObject)
+    : ActiveDOMCallback(globalObject->scriptExecutionContext())
+    , m_constructor(constructor)
+    , m_isolatedWorld(&globalObject->world())
+{
+}
+
+JSCustomElementInterface::~JSCustomElementInterface()
+{
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/WebCore/bindings/js/JSCustomElementInterface.h b/Source/WebCore/bindings/js/JSCustomElementInterface.h
new file mode 100644 (file)
index 0000000..96df1d5
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2015, 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSCustomElementInterface_h
+#define JSCustomElementInterface_h
+
+#if ENABLE(CUSTOM_ELEMENTS)
+
+#include "ActiveDOMCallback.h"
+#include <heap/Weak.h>
+#include <heap/WeakInlines.h>
+#include <runtime/JSObject.h>
+#include <wtf/Forward.h>
+#include <wtf/RefCounted.h>
+#include <wtf/RefPtr.h>
+
+namespace JSC {
+
+class JSObject;
+class PrivateName;
+
+}
+
+namespace WebCore {
+
+class DOMWrapperWorld;
+class Element;
+class JSDOMGlobalObject;
+
+class JSCustomElementInterface : public RefCounted<JSCustomElementInterface>, public ActiveDOMCallback {
+public:
+    static Ref<JSCustomElementInterface> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)
+    {
+        return adoptRef(*new JSCustomElementInterface(callback, globalObject));
+    }
+
+    ScriptExecutionContext* scriptExecutionContext() const { return ContextDestructionObserver::scriptExecutionContext(); }
+    JSC::JSObject* constructor() { return m_constructor.get(); }
+
+    virtual ~JSCustomElementInterface();
+
+private:
+    JSCustomElementInterface(JSC::JSObject* callback, JSDOMGlobalObject*);
+
+    mutable JSC::Weak<JSC::JSObject> m_constructor;
+    RefPtr<DOMWrapperWorld> m_isolatedWorld;
+};
+
+} // namespace WebCore
+
+#endif
+
+#endif
index 094ce3e..aba7e38 100644 (file)
@@ -20,6 +20,7 @@
 #include "config.h"
 #include "JSDocument.h"
 
+#include "CustomElementDefinitions.h"
 #include "ExceptionCode.h"
 #include "Frame.h"
 #include "FrameLoader.h"
@@ -130,4 +131,45 @@ JSValue JSDocument::createTouchList(ExecState& state)
 }
 #endif
 
+#if ENABLE(CUSTOM_ELEMENTS)
+JSValue JSDocument::defineCustomElement(ExecState& state)
+{
+    AtomicString tagName(state.argument(0).toString(&state)->toAtomicString(&state));
+    if (UNLIKELY(state.hadException()))
+        return jsUndefined();
+
+    JSObject* object = state.argument(1).getObject();
+    ConstructData callData;
+    if (!object || object->methodTable()->getConstructData(object, callData) == ConstructTypeNone)
+        return throwTypeError(&state, "The second argument must be a constructor");
+
+    Document& document = wrapped();
+    switch (CustomElementDefinitions::checkName(tagName)) {
+    case CustomElementDefinitions::NameStatus::Valid:
+        break;
+    case CustomElementDefinitions::NameStatus::ConflictsWithBuiltinNames:
+        return throwSyntaxError(&state, "Custom element name cannot be same as one of the builtin elements");
+    case CustomElementDefinitions::NameStatus::NoHyphen:
+        return throwSyntaxError(&state, "Custom element name must contain a hyphen");
+    case CustomElementDefinitions::NameStatus::ContainsUpperCase:
+        return throwSyntaxError(&state, "Custom element name cannot contain an upper case letter");
+    }
+
+    QualifiedName name(nullAtom, tagName, HTMLNames::xhtmlNamespaceURI);
+    auto& definitions = document.ensureCustomElementDefinitions();
+    if (definitions.findInterface(tagName)) {
+        ExceptionCodeWithMessage ec;
+        ec.code = NOT_SUPPORTED_ERR;
+        ec.message = "Cannot define multiple custom elements with the same tag name";
+        setDOMException(&state, ec);
+        return jsUndefined();
+    }
+    definitions.defineElement(name, JSCustomElementInterface::create(object, globalObject()));
+    PrivateName uniquePrivateName;
+    globalObject()->putDirect(globalObject()->vm(), uniquePrivateName, object);
+
+    return jsUndefined();
+}
+#endif
+
 } // namespace WebCore
index 5836a10..abe9f72 100644 (file)
 #include "config.h"
 #include "JSHTMLElement.h"
 
+#include "CustomElementDefinitions.h"
 #include "Document.h"
 #include "HTMLFormElement.h"
+#include <runtime/InternalFunction.h>
 #include <runtime/JSWithScope.h>
 
 namespace WebCore {
 
 using namespace JSC;
 
+#if ENABLE(CUSTOM_ELEMENTS)
+EncodedJSValue JSC_HOST_CALL constructJSHTMLElement(ExecState* state)
+{
+    auto* jsConstructor = jsCast<DOMConstructorObject*>(state->callee());
+
+    auto* context = jsConstructor->scriptExecutionContext();
+    if (!is<Document>(context))
+        return throwConstructorDocumentUnavailableError(*state, "HTMLElement");
+    auto& document = downcast<Document>(*context);
+
+    auto* definitions = document.customElementDefinitions();
+    if (!definitions)
+        return throwVMTypeError(state, "new.target is not a valid custom element constructor");
+
+    VM& vm = state->vm();
+    JSValue newTargetValue = state->thisValue();
+    JSObject* newTarget = newTargetValue.getObject();
+    QualifiedName fullName = definitions->findName(newTarget);
+    if (fullName == nullQName()) {
+        if (UNLIKELY(state->argumentCount() < 1))
+            return throwVMError(state, createNotEnoughArgumentsError(state));
+    }
+
+    if (state->argumentCount()) {
+        String name;
+        if (!state->argument(0).getString(state, name))
+            return throwVMTypeError(state, "The first argument is not a valid custom element name");
+        
+        auto* interface = definitions->findInterface(name);
+        if (!interface)
+            return throwVMTypeError(state, "The first argument is not a valid custom element name");
+        
+        if (newTarget != interface->constructor())
+            return throwVMTypeError(state, "Attempt to construct a custom element with a wrong interface");
+        
+        fullName = QualifiedName(nullAtom, name, HTMLNames::xhtmlNamespaceURI);
+    }
+
+    auto* globalObject = jsConstructor->globalObject();
+    Structure* baseStructure = getDOMStructure<JSHTMLElement>(vm, *globalObject);
+    auto* newElementStructure = InternalFunction::createSubclassStructure(state, newTargetValue, baseStructure);
+    if (UNLIKELY(state->hadException()))
+        return JSValue::encode(jsUndefined());
+
+    Ref<HTMLElement> element = HTMLElement::create(fullName, document);
+    auto* jsElement = JSHTMLElement::create(newElementStructure, globalObject, element.get());
+    cacheWrapper(globalObject->world(), element.ptr(), jsElement);
+    return JSValue::encode(jsElement);
+}
+#endif
+
 JSScope* JSHTMLElement::pushEventHandlerScope(ExecState* exec, JSScope* scope) const
 {
     HTMLElement& element = wrapped();
diff --git a/Source/WebCore/dom/CustomElementDefinitions.cpp b/Source/WebCore/dom/CustomElementDefinitions.cpp
new file mode 100644 (file)
index 0000000..96f6196
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "CustomElementDefinitions.h"
+
+#if ENABLE(CUSTOM_ELEMENTS)
+
+#include "Document.h"
+#include "Element.h"
+#include "JSCustomElementInterface.h"
+#include "MathMLNames.h"
+#include "QualifiedName.h"
+#include "SVGNames.h"
+#include <runtime/JSCJSValueInlines.h>
+#include <wtf/text/AtomicString.h>
+
+namespace WebCore {
+
+CustomElementDefinitions::NameStatus CustomElementDefinitions::checkName(const AtomicString& tagName)
+{
+    bool containsHyphen = false;
+    for (unsigned i = 0; i < tagName.length(); i++) {
+        if (isASCIIUpper(tagName[i]))
+            return NameStatus::ContainsUpperCase;
+        if (tagName[i] == '-')
+            containsHyphen = true;
+    }
+
+    if (!containsHyphen)
+        return NameStatus::NoHyphen;
+
+    // FIXME: We should be taking the advantage of QualifiedNames in SVG and MathML.
+    if (tagName == SVGNames::color_profileTag.localName()
+        || tagName == SVGNames::font_faceTag.localName()
+        || tagName == SVGNames::font_face_formatTag.localName()
+        || tagName == SVGNames::font_face_nameTag.localName()
+        || tagName == SVGNames::font_face_srcTag.localName()
+        || tagName == SVGNames::font_face_uriTag.localName()
+        || tagName == SVGNames::missing_glyphTag.localName()
+#if ENABLE(MATHML)
+        || tagName == MathMLNames::annotation_xmlTag.localName()
+#endif
+        )
+        return NameStatus::ConflictsWithBuiltinNames;
+
+    return NameStatus::Valid;
+}
+
+bool CustomElementDefinitions::defineElement(const QualifiedName& fullName, Ref<JSCustomElementInterface>&& interface)
+{
+    ASSERT(!m_nameMap.contains(fullName.localName()));
+    auto* constructor = interface->constructor();
+    m_nameMap.add(fullName.localName(), CustomElementInfo(fullName, WTFMove(interface)));
+
+    auto addResult = m_constructorMap.add(constructor, fullName);
+    if (!addResult.isNewEntry)
+        addResult.iterator->value = nullQName(); // The interface has multiple tag names associated with it.
+
+    return true;
+}
+
+JSCustomElementInterface* CustomElementDefinitions::findInterface(const AtomicString& name) const
+{
+    auto it = m_nameMap.find(name);
+    return it == m_nameMap.end() ? nullptr : it->value.interface.get();
+}
+
+const QualifiedName& CustomElementDefinitions::findName(const JSC::JSObject* constructor) const
+{
+    auto it = m_constructorMap.find(constructor);
+    return it == m_constructorMap.end() ? nullQName() : it->value;
+}
+
+}
+
+#endif
diff --git a/Source/WebCore/dom/CustomElementDefinitions.h b/Source/WebCore/dom/CustomElementDefinitions.h
new file mode 100644 (file)
index 0000000..88459f7
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2015, 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "JSCustomElementInterface.h"
+#include "QualifiedName.h"
+#include <wtf/HashMap.h>
+#include <wtf/text/AtomicString.h>
+#include <wtf/text/AtomicStringHash.h>
+
+#ifndef CustomElementDefinitions_h
+#define CustomElementDefinitions_h
+
+#if ENABLE(CUSTOM_ELEMENTS)
+
+namespace JSC {
+
+class JSObject;
+    
+}
+
+namespace WebCore {
+
+class Element;
+class QualifiedName;
+
+class CustomElementDefinitions {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    bool defineElement(const QualifiedName&, Ref<JSCustomElementInterface>&&);
+
+    JSCustomElementInterface* findInterface(const AtomicString&) const;
+    const QualifiedName& findName(const JSC::JSObject*) const;
+
+    enum class NameStatus { Valid, ConflictsWithBuiltinNames, NoHyphen, ContainsUpperCase };
+    static NameStatus checkName(const AtomicString& tagName);
+
+private:
+    class CustomElementInfo {
+        WTF_MAKE_FAST_ALLOCATED;
+    public:
+        QualifiedName fullName;
+        RefPtr<JSCustomElementInterface> interface;
+
+        CustomElementInfo()
+            : fullName(nullQName())
+        { }
+
+        CustomElementInfo(const QualifiedName& name, Ref<JSCustomElementInterface>&& interface)
+            : fullName(name)
+            , interface(WTFMove(interface))
+        { }
+    };
+
+    HashMap<AtomicString, CustomElementInfo> m_nameMap;
+    HashMap<const JSC::JSObject*, QualifiedName> m_constructorMap;
+};
+    
+}
+
+#endif
+
+#endif /* CustomElementDefinitions_h */
index 03f9113..c724358 100644 (file)
@@ -44,6 +44,7 @@
 #include "CompositionEvent.h"
 #include "ContentSecurityPolicy.h"
 #include "CookieJar.h"
+#include "CustomElementDefinitions.h"
 #include "CustomEvent.h"
 #include "DOMImplementation.h"
 #include "DOMNamedFlowCollection.h"
@@ -6352,6 +6353,15 @@ unsigned Document::touchEventHandlerCount() const
 #endif
 }
 
+#if ENABLE(CUSTOM_ELEMENTS)
+CustomElementDefinitions& Document::ensureCustomElementDefinitions()
+{
+    if (!m_customElementDefinitions)
+        m_customElementDefinitions = std::make_unique<CustomElementDefinitions>();
+    return *m_customElementDefinitions;
+}
+#endif
+
 LayoutRect Document::absoluteEventHandlerBounds(bool& includesFixedPositionElements)
 {
     includesFixedPositionElements = false;
index 734e327..16cd373 100644 (file)
@@ -175,6 +175,10 @@ enum class ShouldOpenExternalURLsPolicy;
 class TransformSource;
 #endif
 
+#if ENABLE(CUSTOM_ELEMENTS)
+class CustomElementDefinitions;
+#endif
+
 #if ENABLE(DASHBOARD_SUPPORT)
 struct AnnotatedRegionValue;
 #endif
@@ -1214,6 +1218,11 @@ public:
 #endif
     }
 
+#if ENABLE(CUSTOM_ELEMENTS)
+    CustomElementDefinitions* customElementDefinitions() { return m_customElementDefinitions.get(); }
+    CustomElementDefinitions& ensureCustomElementDefinitions();
+#endif
+
     const EventTargetSet* wheelEventTargets() const { return m_wheelEventTargets.get(); }
 
     typedef std::pair<Region, bool> RegionFixedPair;
@@ -1747,6 +1756,10 @@ private:
     Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
 #endif
 
+#if ENABLE(CUSTOM_ELEMENTS)
+    std::unique_ptr<CustomElementDefinitions> m_customElementDefinitions;
+#endif
+
     RefPtr<CSSFontSelector> m_fontSelector;
 
 #if ENABLE(FONT_LOAD_EVENTS)
index e26ec04..af9c45b 100644 (file)
     [NewObject, Custom, RaisesException] TouchList createTouchList();
 #endif
 
+#if defined(LANGUAGE_JAVASCRIPT) && LANGUAGE_JAVASCRIPT
+    [Custom, RaisesException, Conditional=CUSTOM_ELEMENTS]
+    void defineCustomElement(DOMString tagName, CustomElementInterface elementInterface);
+#endif
+
     // Page visibility API.
     readonly attribute DOMString visibilityState;
     readonly attribute boolean hidden;
index 8eef6ff..d914bf6 100644 (file)
@@ -19,6 +19,9 @@
  */
 
 [
+#if defined(ENABLE_CUSTOM_ELEMENTS) && ENABLE_CUSTOM_ELEMENTS
+    CustomConstructor(optional DOMString localName),
+#endif
     JSGenerateToNativeObject,
     JSCustomPushEventHandlerScope,
 ] interface HTMLElement : Element {