Load stylesheets in link elements inside a connected shadow tree
authorrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 2 Nov 2016 21:34:58 +0000 (21:34 +0000)
committerrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 2 Nov 2016 21:34:58 +0000 (21:34 +0000)
https://bugs.webkit.org/show_bug.cgi?id=160683
<rdar://problem/29040652>

Reviewed by Antti Koivisto.

Source/WebCore:

Allow external stylesheets within a shadow tree by storing the appropriate style scope in HTMLLinkElement
when it's connected to a document instead of always talking to document's style scope.

Also improve ShadowRoot's insertedInto and removedFrom so that they only try to add and remove itself from
m_inDocumentShadowRoots when the connected-ness changes.

This patch also removes the superfluous call to notifyChildNodeRemoved in Element::removeShadowRoot to
avoid invoking notifyChildNodeRemoved during a document teardown, which is incorrect. It's sufficient that
~ShadowRoot calls ContainerNode::removeDetachedChildren(), and in turn removeDetachedChildrenInContainer()
since the latter function tears down nodes via the deletion queue during a document destruction and use
notifyChildNodeRemoved() on nodes that outlive the shadow root.

Tests: fast/shadow-dom/link-element-in-shadow-tree.html
       fast/shadow-dom/selected-stylesheet-in-shadow-tree.html

       * dom/Document.cpp:
       (WebCore::Document::didInsertInDocumentShadowRoot): Assert that the shadow root is not in the set.
       (WebCore::Document::didRemoveInDocumentShadowRoot): Assert that the shadow root is not in the document as
       this function is now called after Node::removedFrom in ShadowRoot::removedFrom.
       * dom/Element.cpp:
       (WebCore::Element::removeShadowRoot): See the description above.
       * dom/ShadowRoot.cpp:
       (WebCore::ShadowRoot::insertedInto): Only call didInsertInDocumentShadowRoot when the this shadow root is
       newly connected to a document so we can add assertions in didInsertInDocumentShadowRoot.
       (WebCore::ShadowRoot::removedFrom): Ditto for the removal.
       * html/HTMLLinkElement.cpp:
       (WebCore::HTMLLinkElement::HTMLLinkElement):
       (WebCore::HTMLLinkElement::~HTMLLinkElement):
       (WebCore::HTMLLinkElement::setDisabledState): Exit early when the element is not in a document as invoking
       didChangeActiveStyleSheetCandidates would require having a valid m_styleScope and process() already exits
       early when inDocument() is false.
       (WebCore::HTMLLinkElement::parseAttribute):
       (WebCore::HTMLLinkElement::process): Removed the early exit for when the element is in a shadow tree.
       (WebCore::HTMLLinkElement::insertedInto): Exit early unless this element has just become connected to
       a document instead of whenever its self-inclusive ancestor is inserted into a container.
       (WebCore::HTMLLinkElement::removedFrom): Ditto for removal. Also call removeStyleSheetCandidateNode after
       calling removePendingSheet since the latter depends on m_styleScope being not null.
       (WebCore::HTMLLinkElement::addPendingSheet):
       (WebCore::HTMLLinkElement::removePendingSheet):
       * html/HTMLLinkElement.h:
       * html/HTMLStyleElement.cpp:
       (WebCore::HTMLStyleElement::insertedInto): Only call inline style owner's insertedIntoDocument if this
       element has just become connected to a document.
       (WebCore::HTMLStyleElement::removedFrom): Ditto for the removal.
       * style/StyleScope.h:
       * svg/SVGStyleElement.cpp:
       (WebCore::SVGStyleElement::insertedInto): Ditto.
       (WebCore::SVGStyleElement::removedFrom): Ditto for the removal.

LayoutTests:

Added W3C style testharness.js tests for loading stylesheets via a link element inside a ahadow tree.

* fast/shadow-dom/link-element-in-shadow-tree-expected.txt: Added.
* fast/shadow-dom/link-element-in-shadow-tree.html: Added.
* fast/shadow-dom/resources/green-host.css: Added.
* fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt: Added.
* fast/shadow-dom/selected-stylesheet-in-shadow-tree.html: Added.

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

14 files changed:
LayoutTests/ChangeLog
LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt [new file with mode: 0644]
LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html [new file with mode: 0644]
LayoutTests/fast/shadow-dom/resources/green-host.css [new file with mode: 0644]
LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt [new file with mode: 0644]
LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html [new file with mode: 0644]
Source/WebCore/ChangeLog
Source/WebCore/dom/Document.cpp
Source/WebCore/dom/Element.cpp
Source/WebCore/dom/ShadowRoot.cpp
Source/WebCore/html/HTMLLinkElement.cpp
Source/WebCore/html/HTMLLinkElement.h
Source/WebCore/html/HTMLStyleElement.cpp
Source/WebCore/svg/SVGStyleElement.cpp

index 1322196..a4065b0 100644 (file)
@@ -1,3 +1,19 @@
+2016-11-02  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Load stylesheets in link elements inside a connected shadow tree
+        https://bugs.webkit.org/show_bug.cgi?id=160683
+        <rdar://problem/29040652>
+
+        Reviewed by Antti Koivisto.
+
+        Added W3C style testharness.js tests for loading stylesheets via a link element inside a ahadow tree.
+
+        * fast/shadow-dom/link-element-in-shadow-tree-expected.txt: Added.
+        * fast/shadow-dom/link-element-in-shadow-tree.html: Added.
+        * fast/shadow-dom/resources/green-host.css: Added.
+        * fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt: Added.
+        * fast/shadow-dom/selected-stylesheet-in-shadow-tree.html: Added.
+
 2016-11-02  Alex Christensen  <achristensen@webkit.org>
 
         Remove Battery Status API from the tree
diff --git a/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt b/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt
new file mode 100644 (file)
index 0000000..fedfae8
--- /dev/null
@@ -0,0 +1,12 @@
+
+PASS Link elements should load stylesheets inside a connected shadow tree with closed mode 
+PASS Link elements should load stylesheets inside a connected shadow tree with open mode 
+PASS Link elements must not load stylesheets inside a disconnceted shadow tree with closed mode 
+PASS Link elements must not load stylesheets inside a disconnceted shadow tree with open mode 
+PASS Style rules loaded inside a shadow tree with closed mode must apply to a div in the shadow tree 
+PASS Style rules loaded inside a shadow tree with open mode must apply to a div in the shadow tree 
+PASS :host style rules loaded inside a shadow tree with closed mode must apply to the host element 
+PASS :host style rules loaded inside a shadow tree with open mode must apply to the host element 
+PASS Link elements should load stylesheets inside a connected shadow tree with closed mode 
+PASS Link elements should load stylesheets inside a connected shadow tree with open mode 
+
diff --git a/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html b/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html
new file mode 100644 (file)
index 0000000..fadb539
--- /dev/null
@@ -0,0 +1,143 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Shadow DOM: Link elements should load stylesheets inside shadow trees</title>
+<meta name="author" title="Ryosuke Niwa" href="mailto:rniwa@webkit.org">
+<meta name="assert" content="Link elements should load inside shadow trees">
+<script src='../../resources/testharness.js'></script>
+<script src='../../resources/testharnessreport.js'></script>
+</head>
+<body>
+<script>
+
+function wait_for_onload(element, callback = null) {
+    return new Promise(function (resolve, reject) {
+        element.onload = resolve;
+        element.onerror = reject;
+        setTimeout(() => reject('timeout'), 100);
+        if (callback)
+            return callback();
+    });
+}
+
+let test_iframe;
+function create_iframe() {
+    if (test_iframe)
+        test_iframe.remove();
+
+    test_iframe = document.createElement('iframe');
+    return wait_for_onload().then(() => test_iframe.contentWindow, () => {
+        document.body.appendChild(test_iframe);
+    }).then(function () {
+        const doc = test_iframe.contentWindow.document;
+        doc.open();
+        doc.write('<!DOCTYPE html><html><head><body>');
+        doc.close();
+        return test_iframe.contentWindow;
+    });
+}
+
+add_result_callback(() => {
+    if (test_iframe)
+        test_iframe.remove();
+});
+
+function test_stylesheet_load_in_connected_shadow_tree(mode) {
+    promise_test(() => {
+        return create_iframe().then(contentWindow => {
+            const doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const link = doc.createElement('link');
+            return wait_for_onload(link, () => {
+                link.rel = 'stylesheet';
+                link.href = 'resources/green-host.css';
+                host.attachShadow({mode: mode}).appendChild(link);
+                contentWindow.document.body.appendChild(host);
+            });
+        });
+    }, `Link elements should load stylesheets inside a connected shadow tree with ${mode} mode`);
+}
+
+test_stylesheet_load_in_connected_shadow_tree('closed');
+test_stylesheet_load_in_connected_shadow_tree('open');
+
+function test_stylesheet_do_not_load_in_disconnected_shadow_tree(mode) {
+    promise_test(() => {
+        return create_iframe().then((contentWindow) => {
+            const doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const link = doc.createElement('link');
+            return wait_for_onload(link, () => {
+                link.rel = 'stylesheet';
+                link.href = 'resources/green-host.css';
+                host.attachShadow({mode: mode}).appendChild(link);
+            });
+        }).then(() => {
+            assert_true(false, 'stylesheet must not load inside a disconnected shadow tree');
+        }, (error) => {
+            assert_equals(error, 'timeout');
+        });
+    }, `Link elements must not load stylesheets inside a disconnceted shadow tree with ${mode} mode`);
+}
+
+test_stylesheet_do_not_load_in_disconnected_shadow_tree('closed');
+test_stylesheet_do_not_load_in_disconnected_shadow_tree('open');
+
+function test_loaded_stylesheet_rule_in_shadow_tree_applies_to_div(mode) {
+    promise_test(() => {
+        let div;
+        return create_iframe().then(function (contentWindow) {
+            const doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const shadowRoot = host.attachShadow({mode: mode});
+            shadowRoot.innerHTML = '<link rel="stylesheet" href="resources/green-host.css"><div>';
+            div = shadowRoot.querySelector('div');
+            return wait_for_onload(shadowRoot.querySelector('link'), () => { doc.body.appendChild(host) });
+        }).then(() => {
+            assert_equals(getComputedStyle(div).color, 'rgb(0, 128, 0)');
+        });
+    }, `Style rules loaded inside a shadow tree with ${mode} mode must apply to a div in the shadow tree`);
+}
+
+test_loaded_stylesheet_rule_in_shadow_tree_applies_to_div('closed');
+test_loaded_stylesheet_rule_in_shadow_tree_applies_to_div('open');
+
+function test_loaded_stylesheet_rule_in_shadow_tree_applies_to_host(mode) {
+    promise_test(() => {
+        let host;
+        return create_iframe().then(function (contentWindow) {
+            const doc = contentWindow.document;
+            host = doc.createElement('div');
+            const shadowRoot = host.attachShadow({mode: mode});
+            shadowRoot.innerHTML = '<link rel="stylesheet" href="resources/green-host.css"><div>';
+            return wait_for_onload(shadowRoot.querySelector('link'), () => { doc.body.appendChild(host) });
+        }).then(() => {
+            assert_equals(getComputedStyle(host).color, 'rgb(0, 128, 0)');
+        });
+    }, `:host style rules loaded inside a shadow tree with ${mode} mode must apply to the host element`);
+}
+
+test_loaded_stylesheet_rule_in_shadow_tree_applies_to_host('closed');
+test_loaded_stylesheet_rule_in_shadow_tree_applies_to_host('open');
+
+function test_title_is_ignored_in_shadow_tree(mode) {
+    promise_test(() => {
+        let doc;
+        return create_iframe().then((contentWindow) => {
+            doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const shadowRoot = host.attachShadow({mode: mode});
+            shadowRoot.innerHTML = `<style title="foo"></style>`;
+            doc.body.appendChild(host);
+        }).then(() => {
+            assert_equals(doc.selectedStylesheetSet, null);
+        });
+    }, `Link elements should load stylesheets inside a connected shadow tree with ${mode} mode`);
+}
+
+test_title_is_ignored_in_shadow_tree('closed');
+test_title_is_ignored_in_shadow_tree('open');
+
+</script>
+</html>
+</body>
diff --git a/LayoutTests/fast/shadow-dom/resources/green-host.css b/LayoutTests/fast/shadow-dom/resources/green-host.css
new file mode 100644 (file)
index 0000000..2d030a1
--- /dev/null
@@ -0,0 +1,9 @@
+:host, div {
+    /* For the ease of debugging. */
+    display: inline-block;
+    width: 100px;
+    height: 100px;
+
+    color: green;
+    background: green;
+}
diff --git a/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt b/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt
new file mode 100644 (file)
index 0000000..d7fe0d4
--- /dev/null
@@ -0,0 +1,8 @@
+
+PASS The title attribute on the style element in a document must set the preferred stylesheet. 
+PASS The title attribute on the style element inside a closed shadow tree must not set the preferred stylesheet. 
+PASS The title attribute on the style element inside an open shadow tree must not set the preferred stylesheet. 
+PASS The title attribute on the link element in a document must set the preferred stylesheet. 
+PASS The title attribute on the link element inside a closed shadow tree must not set the preferred stylesheet. 
+PASS The title attribute on the link element inside an open shadow tree must not set the preferred stylesheet. 
+
diff --git a/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html b/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html
new file mode 100644 (file)
index 0000000..b2e3a2c
--- /dev/null
@@ -0,0 +1,99 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Shadow DOM: Link and style elements inside a shadow tree should not affect the preferred stylesheet</title>
+<meta name="author" title="Ryosuke Niwa" href="mailto:rniwa@webkit.org">
+<meta name="assert" content="Link and style elements inside a shadow tree should not affect the preferred stylesheet">
+<script src='../../resources/testharness.js'></script>
+<script src='../../resources/testharnessreport.js'></script>
+</head>
+<body>
+<script>
+
+function make_iframe(markup, testFunction) {
+    return () => {
+        const iframe = document.createElement('iframe');
+        return new Promise(function (resolve) {
+            iframe.onload = () => { resolve(iframe.contentDocument); };
+            document.body.appendChild(iframe);
+        }).then(function (doc) {
+            doc.open();
+            doc.write(markup);
+            doc.close();
+            return testFunction(doc, doc.querySelector('div'));
+        }).then(() => iframe.remove(), error => {
+            iframe.remove();
+            return Promise.reject(error);
+        });
+    };
+}
+
+// Some browsers don't synchronously update the selected stylesheet. 
+function wait_for_stylesheet_to_be_selected() {
+    return new Promise(function (resolve) {
+        setTimeout(resolve, 0);
+    });
+}
+
+promise_test(make_iframe(`<!DOCTYPE html><body>`, (doc) => {
+    doc.body.innerHTML = `<style title="foo">div { color: red; }</style>`;
+    return wait_for_stylesheet_to_be_selected().then(() => {
+        assert_equals(doc.preferredStylesheetSet, 'foo');
+        assert_equals(doc.selectedStylesheetSet, 'foo');
+    });
+}), 'The title attribute on the style element in a document must set the preferred stylesheet.');
+
+promise_test(make_iframe(`<!DOCTYPE html><body><div>`, (doc) => {
+    doc.querySelector('div').attachShadow({mode: 'closed'}).innerHTML = `<style title="foo"></style>`;
+    return wait_for_stylesheet_to_be_selected().then(() => {
+        assert_equals(doc.preferredStylesheetSet, null);
+        assert_equals(doc.selectedStylesheetSet, null);
+    });
+}), 'The title attribute on the style element inside a closed shadow tree must not set the preferred stylesheet.');
+
+promise_test(make_iframe(`<!DOCTYPE html><body><div>`, (doc) => {
+    doc.querySelector('div').attachShadow({mode: 'open'}).innerHTML = `<style title="foo"></style>`;
+    return wait_for_stylesheet_to_be_selected().then(() => {
+        assert_equals(doc.preferredStylesheetSet, null);
+        assert_equals(doc.selectedStylesheetSet, null);
+    });
+}), 'The title attribute on the style element inside an open shadow tree must not set the preferred stylesheet.');
+
+function insert_link_and_wait(parent, title) {
+    return new Promise((resolve, reject) => {
+        const link = parent.ownerDocument.createElement('link');
+        link.rel = 'stylesheet';
+        link.title = title;
+        link.href = 'resources/green-host.css';
+        link.onload = resolve;
+        parent.appendChild(link);
+        setTimeout(() => reject('Failed to load the stylesheet'), 1000);
+    }).then(() => wait_for_stylesheet_to_be_selected());
+}
+
+promise_test(make_iframe(`<!DOCTYPE html><body>`, (doc) => {
+    return insert_link_and_wait(doc.body, 'foo').then(() => {
+        assert_equals(doc.preferredStylesheetSet, 'foo');
+        assert_equals(doc.selectedStylesheetSet, 'foo');
+    });
+}), 'The title attribute on the link element in a document must set the preferred stylesheet.');
+
+promise_test(make_iframe(`<!DOCTYPE html><body><div>`, (doc) => {
+    const root = doc.querySelector('div').attachShadow({mode: 'closed'});
+    return insert_link_and_wait(root, 'foo').then(() => {
+        assert_equals(doc.preferredStylesheetSet, null);
+        assert_equals(doc.selectedStylesheetSet, null);
+    });
+}), 'The title attribute on the link element inside a closed shadow tree must not set the preferred stylesheet.');
+
+promise_test(make_iframe(`<!DOCTYPE html><body><div>`, (doc) => {
+    const root = doc.querySelector('div').attachShadow({mode: 'open'});
+    return insert_link_and_wait(root, 'foo').then(() => {
+        assert_equals(doc.preferredStylesheetSet, null);
+        assert_equals(doc.selectedStylesheetSet, null);
+    });
+}), 'The title attribute on the link element inside an open shadow tree must not set the preferred stylesheet.');
+
+</script>
+</html>
+</body>
index 6f57e84..3680179 100644 (file)
@@ -1,3 +1,60 @@
+2016-11-02  Ryosuke Niwa  <rniwa@webkit.org>
+
+        Load stylesheets in link elements inside a connected shadow tree
+        https://bugs.webkit.org/show_bug.cgi?id=160683
+        <rdar://problem/29040652>
+
+        Reviewed by Antti Koivisto.
+
+        Allow external stylesheets within a shadow tree by storing the appropriate style scope in HTMLLinkElement
+        when it's connected to a document instead of always talking to document's style scope.
+
+        Also improve ShadowRoot's insertedInto and removedFrom so that they only try to add and remove itself from
+        m_inDocumentShadowRoots when the connected-ness changes.
+
+        This patch also removes the superfluous call to notifyChildNodeRemoved in Element::removeShadowRoot to
+        avoid invoking notifyChildNodeRemoved during a document teardown, which is incorrect. It's sufficient that
+        ~ShadowRoot calls ContainerNode::removeDetachedChildren(), and in turn removeDetachedChildrenInContainer()
+        since the latter function tears down nodes via the deletion queue during a document destruction and use
+        notifyChildNodeRemoved() on nodes that outlive the shadow root.
+
+        Tests: fast/shadow-dom/link-element-in-shadow-tree.html
+               fast/shadow-dom/selected-stylesheet-in-shadow-tree.html
+
+       * dom/Document.cpp:
+       (WebCore::Document::didInsertInDocumentShadowRoot): Assert that the shadow root is not in the set.
+       (WebCore::Document::didRemoveInDocumentShadowRoot): Assert that the shadow root is not in the document as
+       this function is now called after Node::removedFrom in ShadowRoot::removedFrom.
+       * dom/Element.cpp:
+       (WebCore::Element::removeShadowRoot): See the description above.
+       * dom/ShadowRoot.cpp:
+       (WebCore::ShadowRoot::insertedInto): Only call didInsertInDocumentShadowRoot when the this shadow root is
+       newly connected to a document so we can add assertions in didInsertInDocumentShadowRoot.
+       (WebCore::ShadowRoot::removedFrom): Ditto for the removal.
+       * html/HTMLLinkElement.cpp:
+       (WebCore::HTMLLinkElement::HTMLLinkElement):
+       (WebCore::HTMLLinkElement::~HTMLLinkElement):
+       (WebCore::HTMLLinkElement::setDisabledState): Exit early when the element is not in a document as invoking
+       didChangeActiveStyleSheetCandidates would require having a valid m_styleScope and process() already exits
+       early when inDocument() is false.
+       (WebCore::HTMLLinkElement::parseAttribute):
+       (WebCore::HTMLLinkElement::process): Removed the early exit for when the element is in a shadow tree.
+       (WebCore::HTMLLinkElement::insertedInto): Exit early unless this element has just become connected to
+       a document instead of whenever its self-inclusive ancestor is inserted into a container.
+       (WebCore::HTMLLinkElement::removedFrom): Ditto for removal. Also call removeStyleSheetCandidateNode after
+       calling removePendingSheet since the latter depends on m_styleScope being not null.
+       (WebCore::HTMLLinkElement::addPendingSheet):
+       (WebCore::HTMLLinkElement::removePendingSheet):
+       * html/HTMLLinkElement.h:
+       * html/HTMLStyleElement.cpp:
+       (WebCore::HTMLStyleElement::insertedInto): Only call inline style owner's insertedIntoDocument if this
+       element has just become connected to a document.
+       (WebCore::HTMLStyleElement::removedFrom): Ditto for the removal.
+       * style/StyleScope.h:
+       * svg/SVGStyleElement.cpp:
+       (WebCore::SVGStyleElement::insertedInto): Ditto.
+       (WebCore::SVGStyleElement::removedFrom): Ditto for the removal.
+
 2016-11-02  Dave Hyatt  <hyatt@apple.com>
 
         [CSS Parser] Clean up new parser's grid layout ifdefs/runtime checking
index d6b204d..609f414 100644 (file)
@@ -6980,11 +6980,13 @@ DOMSelection* Document::getSelection()
 void Document::didInsertInDocumentShadowRoot(ShadowRoot& shadowRoot)
 {
     ASSERT(shadowRoot.inDocument());
+    ASSERT(!m_inDocumentShadowRoots.contains(&shadowRoot));
     m_inDocumentShadowRoots.add(&shadowRoot);
 }
 
 void Document::didRemoveInDocumentShadowRoot(ShadowRoot& shadowRoot)
 {
+    ASSERT(!shadowRoot.inDocument());
     ASSERT(m_inDocumentShadowRoots.contains(&shadowRoot));
     m_inDocumentShadowRoots.remove(&shadowRoot);
 }
index ad77cc5..8989780 100644 (file)
@@ -1784,8 +1784,6 @@ void Element::removeShadowRoot()
 
     oldRoot->setHost(nullptr);
     oldRoot->setParentTreeScope(&document());
-
-    notifyChildNodeRemoved(*this, *oldRoot);
 }
 
 static bool canAttachAuthorShadowRoot(const Element& element)
index 5a096f4..22de954 100644 (file)
@@ -84,17 +84,18 @@ ShadowRoot::~ShadowRoot()
 
 Node::InsertionNotificationRequest ShadowRoot::insertedInto(ContainerNode& insertionPoint)
 {
-    auto result = DocumentFragment::insertedInto(insertionPoint);
-    if (inDocument())
+    bool wasInDocument = inDocument();
+    DocumentFragment::insertedInto(insertionPoint);
+    if (insertionPoint.inDocument() && !wasInDocument)
         document().didInsertInDocumentShadowRoot(*this);
-    return result;
+    return InsertionDone;
 }
 
 void ShadowRoot::removedFrom(ContainerNode& insertionPoint)
 {
-    if (inDocument())
-        document().didRemoveInDocumentShadowRoot(*this);
     DocumentFragment::removedFrom(insertionPoint);
+    if (insertionPoint.inDocument() && !inDocument())
+        document().didRemoveInDocumentShadowRoot(*this);
 }
 
 Style::Scope& ShadowRoot::styleScope()
index ae03f93..9664db4 100644 (file)
@@ -80,7 +80,6 @@ inline HTMLLinkElement::HTMLLinkElement(const QualifiedName& tagName, Document&
     , m_disabledState(Unset)
     , m_loading(false)
     , m_createdByParser(createdByParser)
-    , m_isInShadowTree(false)
     , m_firedLoad(false)
     , m_loadedResource(false)
     , m_pendingSheetType(Unknown)
@@ -101,8 +100,8 @@ HTMLLinkElement::~HTMLLinkElement()
     if (m_cachedSheet)
         m_cachedSheet->removeClient(*this);
 
-    if (inDocument())
-        document().styleScope().removeStyleSheetCandidateNode(*this);
+    if (m_styleScope)
+        m_styleScope->removeStyleSheetCandidateNode(*this);
 
     linkLoadEventSender().cancelEvent(*this);
     linkErrorEventSender().cancelEvent(*this);
@@ -112,35 +111,42 @@ void HTMLLinkElement::setDisabledState(bool disabled)
 {
     DisabledState oldDisabledState = m_disabledState;
     m_disabledState = disabled ? Disabled : EnabledViaScript;
-    if (oldDisabledState != m_disabledState) {
-        // If we change the disabled state while the sheet is still loading, then we have to
-        // perform three checks:
-        if (styleSheetIsLoading()) {
-            // Check #1: The sheet becomes disabled while loading.
-            if (m_disabledState == Disabled)
-                removePendingSheet();
-
-            // Check #2: An alternate sheet becomes enabled while it is still loading.
-            if (m_relAttribute.isAlternate && m_disabledState == EnabledViaScript)
-                addPendingSheet(ActiveSheet);
-
-            // Check #3: A main sheet becomes enabled while it was still loading and
-            // after it was disabled via script. It takes really terrible code to make this
-            // happen (a double toggle for no reason essentially). This happens on
-            // virtualplastic.net, which manages to do about 12 enable/disables on only 3
-            // sheets. :)
-            if (!m_relAttribute.isAlternate && m_disabledState == EnabledViaScript && oldDisabledState == Disabled)
-                addPendingSheet(ActiveSheet);
-
-            // If the sheet is already loading just bail.
-            return;
-        }
+    if (oldDisabledState == m_disabledState)
+        return;
+
+    ASSERT(inDocument() || !styleSheetIsLoading());
+    if (!inDocument())
+        return;
+
+    // If we change the disabled state while the sheet is still loading, then we have to
+    // perform three checks:
+    if (styleSheetIsLoading()) {
+        // Check #1: The sheet becomes disabled while loading.
+        if (m_disabledState == Disabled)
+            removePendingSheet();
+
+        // Check #2: An alternate sheet becomes enabled while it is still loading.
+        if (m_relAttribute.isAlternate && m_disabledState == EnabledViaScript)
+            addPendingSheet(ActiveSheet);
+
+        // Check #3: A main sheet becomes enabled while it was still loading and
+        // after it was disabled via script. It takes really terrible code to make this
+        // happen (a double toggle for no reason essentially). This happens on
+        // virtualplastic.net, which manages to do about 12 enable/disables on only 3
+        // sheets. :)
+        if (!m_relAttribute.isAlternate && m_disabledState == EnabledViaScript && oldDisabledState == Disabled)
+            addPendingSheet(ActiveSheet);
 
-        // Load the sheet, since it's never been loaded before.
-        if (!m_sheet && m_disabledState == EnabledViaScript)
-            process();
-        else
-            document().styleScope().didChangeActiveStyleSheetCandidates();
+        // If the sheet is already loading just bail.
+        return;
+    }
+
+    // Load the sheet, since it's never been loaded before.
+    if (!m_sheet && m_disabledState == EnabledViaScript)
+        process();
+    else {
+        ASSERT(m_styleScope);
+        m_styleScope->didChangeActiveStyleSheetCandidates();
     }
 }
 
@@ -176,7 +182,7 @@ void HTMLLinkElement::parseAttribute(const QualifiedName& name, const AtomicStri
         m_media = value.string().convertToASCIILowercase();
         process();
         if (m_sheet && !isDisabled())
-            document().styleScope().didChangeActiveStyleSheetCandidates();
+            m_styleScope->didChangeActiveStyleSheetCandidates();
         return;
     }
     if (name == disabledAttr) {
@@ -214,7 +220,7 @@ String HTMLLinkElement::crossOrigin() const
 
 void HTMLLinkElement::process()
 {
-    if (!inDocument() || m_isInShadowTree) {
+    if (!inDocument()) {
         ASSERT(!m_sheet);
         return;
     }
@@ -283,7 +289,7 @@ void HTMLLinkElement::process()
     } else if (m_sheet) {
         // we no longer contain a stylesheet, e.g. perhaps rel or type was changed
         clearSheet();
-        document().styleScope().didChangeActiveStyleSheetCandidates();
+        m_styleScope->didChangeActiveStyleSheetCandidates();
     }
 }
 
@@ -297,15 +303,13 @@ void HTMLLinkElement::clearSheet()
 
 Node::InsertionNotificationRequest HTMLLinkElement::insertedInto(ContainerNode& insertionPoint)
 {
+    bool wasInDocument = inDocument();
     HTMLElement::insertedInto(insertionPoint);
-    if (!insertionPoint.inDocument())
-        return InsertionDone;
-
-    m_isInShadowTree = isInShadowTree();
-    if (m_isInShadowTree)
+    if (!insertionPoint.inDocument() || wasInDocument)
         return InsertionDone;
 
-    document().styleScope().addStyleSheetCandidateNode(*this, m_createdByParser);
+    m_styleScope = &Style::Scope::forNode(*this);
+    m_styleScope->addStyleSheetCandidateNode(*this, m_createdByParser);
 
     process();
     return InsertionDone;
@@ -314,20 +318,20 @@ Node::InsertionNotificationRequest HTMLLinkElement::insertedInto(ContainerNode&
 void HTMLLinkElement::removedFrom(ContainerNode& insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-    if (!insertionPoint.inDocument())
+    if (!insertionPoint.inDocument() || inDocument())
         return;
 
-    if (m_isInShadowTree) {
-        ASSERT(!m_sheet);
-        return;
-    }
-    document().styleScope().removeStyleSheetCandidateNode(*this);
-
     if (m_sheet)
         clearSheet();
 
     if (styleSheetIsLoading())
         removePendingSheet(RemovePendingSheetNotifyLater);
+    
+    if (m_styleScope) {
+        m_styleScope->removeStyleSheetCandidateNode(*this);
+        m_styleScope = nullptr;
+    }
+
 }
 
 void HTMLLinkElement::finishParsingChildren()
@@ -544,7 +548,8 @@ void HTMLLinkElement::addPendingSheet(PendingSheetType type)
 
     if (m_pendingSheetType == InactiveSheet)
         return;
-    document().styleScope().addPendingSheet();
+    ASSERT(m_styleScope);
+    m_styleScope->addPendingSheet();
 }
 
 void HTMLLinkElement::removePendingSheet(RemovePendingSheetNotificationType notification)
@@ -555,13 +560,14 @@ void HTMLLinkElement::removePendingSheet(RemovePendingSheetNotificationType noti
     if (type == Unknown)
         return;
 
+    ASSERT(m_styleScope);
     if (type == InactiveSheet) {
         // Document just needs to know about the sheet for exposure through document.styleSheets
-        document().styleScope().didChangeActiveStyleSheetCandidates();
+        m_styleScope->didChangeActiveStyleSheetCandidates();
         return;
     }
 
-    document().styleScope().removePendingSheet(
+    m_styleScope->removePendingSheet(
         notification == RemovePendingSheetNotifyImmediately
         ? Style::Scope::RemovePendingSheetNotifyImmediately
         : Style::Scope::RemovePendingSheetNotifyLater);
index d1ea76d..8471ece 100644 (file)
@@ -119,6 +119,7 @@ private:
     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
 
     LinkLoader m_linkLoader;
+    Style::Scope* m_styleScope { nullptr };
     CachedResourceHandle<CachedCSSStyleSheet> m_cachedSheet;
     RefPtr<CSSStyleSheet> m_sheet;
     enum DisabledState {
@@ -134,7 +135,6 @@ private:
     LinkRelAttribute m_relAttribute;
     bool m_loading;
     bool m_createdByParser;
-    bool m_isInShadowTree;
     bool m_firedLoad;
     bool m_loadedResource;
 
index bd693cd..4e7b09c 100644 (file)
@@ -94,18 +94,17 @@ void HTMLStyleElement::finishParsingChildren()
 
 Node::InsertionNotificationRequest HTMLStyleElement::insertedInto(ContainerNode& insertionPoint)
 {
-    HTMLElement::insertedInto(insertionPoint);
-    if (insertionPoint.inDocument())
+    bool wasInDocument = inDocument();
+    auto result = HTMLElement::insertedInto(insertionPoint);
+    if (insertionPoint.inDocument() && !wasInDocument)
         m_styleSheetOwner.insertedIntoDocument(*this);
-
-    return InsertionDone;
+    return result;
 }
 
 void HTMLStyleElement::removedFrom(ContainerNode& insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-
-    if (insertionPoint.inDocument())
+    if (insertionPoint.inDocument() && !inDocument())
         m_styleSheetOwner.removedFromDocument(*this);
 }
 
index e0b4767..593ab70 100644 (file)
@@ -116,16 +116,17 @@ void SVGStyleElement::finishParsingChildren()
 
 Node::InsertionNotificationRequest SVGStyleElement::insertedInto(ContainerNode& rootParent)
 {
-    SVGElement::insertedInto(rootParent);
-    if (rootParent.inDocument())
+    bool wasInDocument = inDocument();
+    auto result = SVGElement::insertedInto(rootParent);
+    if (rootParent.inDocument() && !wasInDocument)
         m_styleSheetOwner.insertedIntoDocument(*this);
-    return InsertionDone;
+    return result;
 }
 
 void SVGStyleElement::removedFrom(ContainerNode& rootParent)
 {
     SVGElement::removedFrom(rootParent);
-    if (rootParent.inDocument())
+    if (rootParent.inDocument() && !inDocument())
         m_styleSheetOwner.removedFromDocument(*this);
 }