<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[208403] trunk</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.webkit.org/projects/webkit/changeset/208403">208403</a></dd>
<dt>Author</dt> <dd>rniwa@webkit.org</dd>
<dt>Date</dt> <dd>2016-11-04 15:53:33 -0700 (Fri, 04 Nov 2016)</dd>
</dl>

<h3>Log Message</h3>
<pre>Load stylesheets in link elements inside a connected shadow tree
https://bugs.webkit.org/show_bug.cgi?id=160683
&lt;rdar://problem/29040652&gt;

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.

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

       * 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.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkLayoutTestsChangeLog">trunk/LayoutTests/ChangeLog</a></li>
<li><a href="#trunkSourceWebCoreChangeLog">trunk/Source/WebCore/ChangeLog</a></li>
<li><a href="#trunkSourceWebCorehtmlHTMLLinkElementcpp">trunk/Source/WebCore/html/HTMLLinkElement.cpp</a></li>
<li><a href="#trunkSourceWebCorehtmlHTMLLinkElementh">trunk/Source/WebCore/html/HTMLLinkElement.h</a></li>
<li><a href="#trunkSourceWebCorehtmlHTMLStyleElementcpp">trunk/Source/WebCore/html/HTMLStyleElement.cpp</a></li>
<li><a href="#trunkSourceWebCoresvgSVGStyleElementcpp">trunk/Source/WebCore/svg/SVGStyleElement.cpp</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#trunkLayoutTestsfastshadowdomlinkelementinshadowtreeexpectedtxt">trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt</a></li>
<li><a href="#trunkLayoutTestsfastshadowdomlinkelementinshadowtreehtml">trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html</a></li>
<li><a href="#trunkLayoutTestsfastshadowdomresourcesgreenhostcss">trunk/LayoutTests/fast/shadow-dom/resources/green-host.css</a></li>
<li><a href="#trunkLayoutTestsfastshadowdomselectedstylesheetinshadowtreeexpectedtxt">trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt</a></li>
<li><a href="#trunkLayoutTestsfastshadowdomselectedstylesheetinshadowtreehtml">trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkLayoutTestsChangeLog"></a>
<div class="modfile"><h4>Modified: trunk/LayoutTests/ChangeLog (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/ChangeLog        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/LayoutTests/ChangeLog        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -1,3 +1,19 @@
</span><ins>+2016-11-04  Ryosuke Niwa  &lt;rniwa@webkit.org&gt;
+
+        Load stylesheets in link elements inside a connected shadow tree
+        https://bugs.webkit.org/show_bug.cgi?id=160683
+        &lt;rdar://problem/29040652&gt;
+
+        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.
+
</ins><span class="cx"> 2016-11-04  Chris Dumez  &lt;cdumez@apple.com&gt;
</span><span class="cx"> 
</span><span class="cx">         Add layout test for input.setCustomValidity()
</span></span></pre></div>
<a id="trunkLayoutTestsfastshadowdomlinkelementinshadowtreeexpectedtxt"></a>
<div class="addfile"><h4>Added: trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt (0 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt                                (rev 0)
+++ trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree-expected.txt        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -0,0 +1,12 @@
</span><ins>+
+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 
+
</ins></span></pre></div>
<a id="trunkLayoutTestsfastshadowdomlinkelementinshadowtreehtml"></a>
<div class="addfile"><h4>Added: trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html (0 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html                                (rev 0)
+++ trunk/LayoutTests/fast/shadow-dom/link-element-in-shadow-tree.html        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -0,0 +1,143 @@
</span><ins>+&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+&lt;head&gt;
+&lt;title&gt;Shadow DOM: Link elements should load stylesheets inside shadow trees&lt;/title&gt;
+&lt;meta name=&quot;author&quot; title=&quot;Ryosuke Niwa&quot; href=&quot;mailto:rniwa@webkit.org&quot;&gt;
+&lt;meta name=&quot;assert&quot; content=&quot;Link elements should load inside shadow trees&quot;&gt;
+&lt;script src='../../resources/testharness.js'&gt;&lt;/script&gt;
+&lt;script src='../../resources/testharnessreport.js'&gt;&lt;/script&gt;
+&lt;/head&gt;
+&lt;body&gt;
+&lt;script&gt;
+
+function wait_for_onload(element, callback = null) {
+    return new Promise(function (resolve, reject) {
+        element.onload = resolve;
+        element.onerror = reject;
+        setTimeout(() =&gt; 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(() =&gt; test_iframe.contentWindow, () =&gt; {
+        document.body.appendChild(test_iframe);
+    }).then(function () {
+        const doc = test_iframe.contentWindow.document;
+        doc.open();
+        doc.write('&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;body&gt;');
+        doc.close();
+        return test_iframe.contentWindow;
+    });
+}
+
+add_result_callback(() =&gt; {
+    if (test_iframe)
+        test_iframe.remove();
+});
+
+function test_stylesheet_load_in_connected_shadow_tree(mode) {
+    promise_test(() =&gt; {
+        return create_iframe().then(contentWindow =&gt; {
+            const doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const link = doc.createElement('link');
+            return wait_for_onload(link, () =&gt; {
+                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(() =&gt; {
+        return create_iframe().then((contentWindow) =&gt; {
+            const doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const link = doc.createElement('link');
+            return wait_for_onload(link, () =&gt; {
+                link.rel = 'stylesheet';
+                link.href = 'resources/green-host.css';
+                host.attachShadow({mode: mode}).appendChild(link);
+            });
+        }).then(() =&gt; {
+            assert_true(false, 'stylesheet must not load inside a disconnected shadow tree');
+        }, (error) =&gt; {
+            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(() =&gt; {
+        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 = '&lt;link rel=&quot;stylesheet&quot; href=&quot;resources/green-host.css&quot;&gt;&lt;div&gt;';
+            div = shadowRoot.querySelector('div');
+            return wait_for_onload(shadowRoot.querySelector('link'), () =&gt; { doc.body.appendChild(host) });
+        }).then(() =&gt; {
+            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(() =&gt; {
+        let host;
+        return create_iframe().then(function (contentWindow) {
+            const doc = contentWindow.document;
+            host = doc.createElement('div');
+            const shadowRoot = host.attachShadow({mode: mode});
+            shadowRoot.innerHTML = '&lt;link rel=&quot;stylesheet&quot; href=&quot;resources/green-host.css&quot;&gt;&lt;div&gt;';
+            return wait_for_onload(shadowRoot.querySelector('link'), () =&gt; { doc.body.appendChild(host) });
+        }).then(() =&gt; {
+            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(() =&gt; {
+        let doc;
+        return create_iframe().then((contentWindow) =&gt; {
+            doc = contentWindow.document;
+            const host = doc.createElement('div');
+            const shadowRoot = host.attachShadow({mode: mode});
+            shadowRoot.innerHTML = `&lt;style title=&quot;foo&quot;&gt;&lt;/style&gt;`;
+            doc.body.appendChild(host);
+        }).then(() =&gt; {
+            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');
+
+&lt;/script&gt;
+&lt;/html&gt;
+&lt;/body&gt;
</ins></span></pre></div>
<a id="trunkLayoutTestsfastshadowdomresourcesgreenhostcss"></a>
<div class="addfile"><h4>Added: trunk/LayoutTests/fast/shadow-dom/resources/green-host.css (0 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/fast/shadow-dom/resources/green-host.css                                (rev 0)
+++ trunk/LayoutTests/fast/shadow-dom/resources/green-host.css        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -0,0 +1,9 @@
</span><ins>+:host, div {
+    /* For the ease of debugging. */
+    display: inline-block;
+    width: 100px;
+    height: 100px;
+
+    color: green;
+    background: green;
+}
</ins></span></pre></div>
<a id="trunkLayoutTestsfastshadowdomselectedstylesheetinshadowtreeexpectedtxt"></a>
<div class="addfile"><h4>Added: trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt (0 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt                                (rev 0)
+++ trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree-expected.txt        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -0,0 +1,8 @@
</span><ins>+
+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. 
+
</ins></span></pre></div>
<a id="trunkLayoutTestsfastshadowdomselectedstylesheetinshadowtreehtml"></a>
<div class="addfile"><h4>Added: trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html (0 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html                                (rev 0)
+++ trunk/LayoutTests/fast/shadow-dom/selected-stylesheet-in-shadow-tree.html        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -0,0 +1,99 @@
</span><ins>+&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+&lt;head&gt;
+&lt;title&gt;Shadow DOM: Link and style elements inside a shadow tree should not affect the preferred stylesheet&lt;/title&gt;
+&lt;meta name=&quot;author&quot; title=&quot;Ryosuke Niwa&quot; href=&quot;mailto:rniwa@webkit.org&quot;&gt;
+&lt;meta name=&quot;assert&quot; content=&quot;Link and style elements inside a shadow tree should not affect the preferred stylesheet&quot;&gt;
+&lt;script src='../../resources/testharness.js'&gt;&lt;/script&gt;
+&lt;script src='../../resources/testharnessreport.js'&gt;&lt;/script&gt;
+&lt;/head&gt;
+&lt;body&gt;
+&lt;script&gt;
+
+function make_iframe(markup, testFunction) {
+    return () =&gt; {
+        const iframe = document.createElement('iframe');
+        return new Promise(function (resolve) {
+            iframe.onload = () =&gt; { resolve(iframe.contentDocument); };
+            document.body.appendChild(iframe);
+        }).then(function (doc) {
+            doc.open();
+            doc.write(markup);
+            doc.close();
+            return testFunction(doc, doc.querySelector('div'));
+        }).then(() =&gt; iframe.remove(), error =&gt; {
+            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(`&lt;!DOCTYPE html&gt;&lt;body&gt;`, (doc) =&gt; {
+    doc.body.innerHTML = `&lt;style title=&quot;foo&quot;&gt;div { color: red; }&lt;/style&gt;`;
+    return wait_for_stylesheet_to_be_selected().then(() =&gt; {
+        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(`&lt;!DOCTYPE html&gt;&lt;body&gt;&lt;div&gt;`, (doc) =&gt; {
+    doc.querySelector('div').attachShadow({mode: 'closed'}).innerHTML = `&lt;style title=&quot;foo&quot;&gt;&lt;/style&gt;`;
+    return wait_for_stylesheet_to_be_selected().then(() =&gt; {
+        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(`&lt;!DOCTYPE html&gt;&lt;body&gt;&lt;div&gt;`, (doc) =&gt; {
+    doc.querySelector('div').attachShadow({mode: 'open'}).innerHTML = `&lt;style title=&quot;foo&quot;&gt;&lt;/style&gt;`;
+    return wait_for_stylesheet_to_be_selected().then(() =&gt; {
+        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) =&gt; {
+        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(() =&gt; reject('Failed to load the stylesheet'), 1000);
+    }).then(() =&gt; wait_for_stylesheet_to_be_selected());
+}
+
+promise_test(make_iframe(`&lt;!DOCTYPE html&gt;&lt;body&gt;`, (doc) =&gt; {
+    return insert_link_and_wait(doc.body, 'foo').then(() =&gt; {
+        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(`&lt;!DOCTYPE html&gt;&lt;body&gt;&lt;div&gt;`, (doc) =&gt; {
+    const root = doc.querySelector('div').attachShadow({mode: 'closed'});
+    return insert_link_and_wait(root, 'foo').then(() =&gt; {
+        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(`&lt;!DOCTYPE html&gt;&lt;body&gt;&lt;div&gt;`, (doc) =&gt; {
+    const root = doc.querySelector('div').attachShadow({mode: 'open'});
+    return insert_link_and_wait(root, 'foo').then(() =&gt; {
+        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.');
+
+&lt;/script&gt;
+&lt;/html&gt;
+&lt;/body&gt;
</ins></span></pre></div>
<a id="trunkSourceWebCoreChangeLog"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebCore/ChangeLog (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebCore/ChangeLog        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/Source/WebCore/ChangeLog        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -1,3 +1,41 @@
</span><ins>+2016-11-04  Ryosuke Niwa  &lt;rniwa@webkit.org&gt;
+
+        Load stylesheets in link elements inside a connected shadow tree
+        https://bugs.webkit.org/show_bug.cgi?id=160683
+        &lt;rdar://problem/29040652&gt;
+
+        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.
+
+        Tests: fast/shadow-dom/link-element-in-shadow-tree.html
+               fast/shadow-dom/selected-stylesheet-in-shadow-tree.html
+
+       * 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.
+
</ins><span class="cx"> 2016-11-04  Said Abou-Hallawa  &lt;sabouhallawa@apple.com&gt;
</span><span class="cx"> 
</span><span class="cx">         Add a setting and preferences to enable/disable async image decoding
</span></span></pre></div>
<a id="trunkSourceWebCorehtmlHTMLLinkElementcpp"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebCore/html/HTMLLinkElement.cpp (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebCore/html/HTMLLinkElement.cpp        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/Source/WebCore/html/HTMLLinkElement.cpp        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -80,7 +80,6 @@
</span><span class="cx">     , m_disabledState(Unset)
</span><span class="cx">     , m_loading(false)
</span><span class="cx">     , m_createdByParser(createdByParser)
</span><del>-    , m_isInShadowTree(false)
</del><span class="cx">     , m_firedLoad(false)
</span><span class="cx">     , m_loadedResource(false)
</span><span class="cx">     , m_pendingSheetType(Unknown)
</span><span class="lines">@@ -101,8 +100,8 @@
</span><span class="cx">     if (m_cachedSheet)
</span><span class="cx">         m_cachedSheet-&gt;removeClient(*this);
</span><span class="cx"> 
</span><del>-    if (inDocument())
-        document().styleScope().removeStyleSheetCandidateNode(*this);
</del><ins>+    if (m_styleScope)
+        m_styleScope-&gt;removeStyleSheetCandidateNode(*this);
</ins><span class="cx"> 
</span><span class="cx">     linkLoadEventSender().cancelEvent(*this);
</span><span class="cx">     linkErrorEventSender().cancelEvent(*this);
</span><span class="lines">@@ -112,36 +111,43 @@
</span><span class="cx"> {
</span><span class="cx">     DisabledState oldDisabledState = m_disabledState;
</span><span class="cx">     m_disabledState = disabled ? Disabled : EnabledViaScript;
</span><del>-    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();
</del><ins>+    if (oldDisabledState == m_disabledState)
+        return;
</ins><span class="cx"> 
</span><del>-            // Check #2: An alternate sheet becomes enabled while it is still loading.
-            if (m_relAttribute.isAlternate &amp;&amp; m_disabledState == EnabledViaScript)
-                addPendingSheet(ActiveSheet);
</del><ins>+    ASSERT(inDocument() || !styleSheetIsLoading());
+    if (!inDocument())
+        return;
</ins><span class="cx"> 
</span><del>-            // 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 &amp;&amp; m_disabledState == EnabledViaScript &amp;&amp; oldDisabledState == Disabled)
-                addPendingSheet(ActiveSheet);
</del><ins>+    // 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();
</ins><span class="cx"> 
</span><del>-            // If the sheet is already loading just bail.
-            return;
-        }
</del><ins>+        // Check #2: An alternate sheet becomes enabled while it is still loading.
+        if (m_relAttribute.isAlternate &amp;&amp; m_disabledState == EnabledViaScript)
+            addPendingSheet(ActiveSheet);
</ins><span class="cx"> 
</span><del>-        // Load the sheet, since it's never been loaded before.
-        if (!m_sheet &amp;&amp; m_disabledState == EnabledViaScript)
-            process();
-        else
-            document().styleScope().didChangeActiveStyleSheetCandidates();
</del><ins>+        // 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 &amp;&amp; m_disabledState == EnabledViaScript &amp;&amp; oldDisabledState == Disabled)
+            addPendingSheet(ActiveSheet);
+
+        // If the sheet is already loading just bail.
+        return;
</ins><span class="cx">     }
</span><ins>+
+    // Load the sheet, since it's never been loaded before.
+    if (!m_sheet &amp;&amp; m_disabledState == EnabledViaScript)
+        process();
+    else {
+        ASSERT(m_styleScope);
+        m_styleScope-&gt;didChangeActiveStyleSheetCandidates();
+    }
</ins><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void HTMLLinkElement::parseAttribute(const QualifiedName&amp; name, const AtomicString&amp; value)
</span><span class="lines">@@ -176,7 +182,7 @@
</span><span class="cx">         m_media = value.string().convertToASCIILowercase();
</span><span class="cx">         process();
</span><span class="cx">         if (m_sheet &amp;&amp; !isDisabled())
</span><del>-            document().styleScope().didChangeActiveStyleSheetCandidates();
</del><ins>+            m_styleScope-&gt;didChangeActiveStyleSheetCandidates();
</ins><span class="cx">         return;
</span><span class="cx">     }
</span><span class="cx">     if (name == disabledAttr) {
</span><span class="lines">@@ -214,7 +220,7 @@
</span><span class="cx"> 
</span><span class="cx"> void HTMLLinkElement::process()
</span><span class="cx"> {
</span><del>-    if (!inDocument() || m_isInShadowTree) {
</del><ins>+    if (!inDocument()) {
</ins><span class="cx">         ASSERT(!m_sheet);
</span><span class="cx">         return;
</span><span class="cx">     }
</span><span class="lines">@@ -283,7 +289,7 @@
</span><span class="cx">     } else if (m_sheet) {
</span><span class="cx">         // we no longer contain a stylesheet, e.g. perhaps rel or type was changed
</span><span class="cx">         clearSheet();
</span><del>-        document().styleScope().didChangeActiveStyleSheetCandidates();
</del><ins>+        m_styleScope-&gt;didChangeActiveStyleSheetCandidates();
</ins><span class="cx">     }
</span><span class="cx"> }
</span><span class="cx"> 
</span><span class="lines">@@ -297,16 +303,14 @@
</span><span class="cx"> 
</span><span class="cx"> Node::InsertionNotificationRequest HTMLLinkElement::insertedInto(ContainerNode&amp; insertionPoint)
</span><span class="cx"> {
</span><ins>+    bool wasInDocument = inDocument();
</ins><span class="cx">     HTMLElement::insertedInto(insertionPoint);
</span><del>-    if (!insertionPoint.inDocument())
</del><ins>+    if (!insertionPoint.inDocument() || wasInDocument)
</ins><span class="cx">         return InsertionDone;
</span><span class="cx"> 
</span><del>-    m_isInShadowTree = isInShadowTree();
-    if (m_isInShadowTree)
-        return InsertionDone;
</del><ins>+    m_styleScope = &amp;Style::Scope::forNode(*this);
+    m_styleScope-&gt;addStyleSheetCandidateNode(*this, m_createdByParser);
</ins><span class="cx"> 
</span><del>-    document().styleScope().addStyleSheetCandidateNode(*this, m_createdByParser);
-
</del><span class="cx">     process();
</span><span class="cx">     return InsertionDone;
</span><span class="cx"> }
</span><span class="lines">@@ -314,20 +318,20 @@
</span><span class="cx"> void HTMLLinkElement::removedFrom(ContainerNode&amp; insertionPoint)
</span><span class="cx"> {
</span><span class="cx">     HTMLElement::removedFrom(insertionPoint);
</span><del>-    if (!insertionPoint.inDocument())
</del><ins>+    if (!insertionPoint.inDocument() || inDocument())
</ins><span class="cx">         return;
</span><span class="cx"> 
</span><del>-    if (m_isInShadowTree) {
-        ASSERT(!m_sheet);
-        return;
-    }
-    document().styleScope().removeStyleSheetCandidateNode(*this);
-
</del><span class="cx">     if (m_sheet)
</span><span class="cx">         clearSheet();
</span><span class="cx"> 
</span><span class="cx">     if (styleSheetIsLoading())
</span><span class="cx">         removePendingSheet(RemovePendingSheetNotifyLater);
</span><ins>+    
+    if (m_styleScope) {
+        m_styleScope-&gt;removeStyleSheetCandidateNode(*this);
+        m_styleScope = nullptr;
+    }
+
</ins><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void HTMLLinkElement::finishParsingChildren()
</span><span class="lines">@@ -544,7 +548,8 @@
</span><span class="cx"> 
</span><span class="cx">     if (m_pendingSheetType == InactiveSheet)
</span><span class="cx">         return;
</span><del>-    document().styleScope().addPendingSheet();
</del><ins>+    ASSERT(m_styleScope);
+    m_styleScope-&gt;addPendingSheet();
</ins><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void HTMLLinkElement::removePendingSheet(RemovePendingSheetNotificationType notification)
</span><span class="lines">@@ -555,13 +560,14 @@
</span><span class="cx">     if (type == Unknown)
</span><span class="cx">         return;
</span><span class="cx"> 
</span><ins>+    ASSERT(m_styleScope);
</ins><span class="cx">     if (type == InactiveSheet) {
</span><span class="cx">         // Document just needs to know about the sheet for exposure through document.styleSheets
</span><del>-        document().styleScope().didChangeActiveStyleSheetCandidates();
</del><ins>+        m_styleScope-&gt;didChangeActiveStyleSheetCandidates();
</ins><span class="cx">         return;
</span><span class="cx">     }
</span><span class="cx"> 
</span><del>-    document().styleScope().removePendingSheet(
</del><ins>+    m_styleScope-&gt;removePendingSheet(
</ins><span class="cx">         notification == RemovePendingSheetNotifyImmediately
</span><span class="cx">         ? Style::Scope::RemovePendingSheetNotifyImmediately
</span><span class="cx">         : Style::Scope::RemovePendingSheetNotifyLater);
</span></span></pre></div>
<a id="trunkSourceWebCorehtmlHTMLLinkElementh"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebCore/html/HTMLLinkElement.h (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebCore/html/HTMLLinkElement.h        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/Source/WebCore/html/HTMLLinkElement.h        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -119,6 +119,7 @@
</span><span class="cx">     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
</span><span class="cx"> 
</span><span class="cx">     LinkLoader m_linkLoader;
</span><ins>+    Style::Scope* m_styleScope { nullptr };
</ins><span class="cx">     CachedResourceHandle&lt;CachedCSSStyleSheet&gt; m_cachedSheet;
</span><span class="cx">     RefPtr&lt;CSSStyleSheet&gt; m_sheet;
</span><span class="cx">     enum DisabledState {
</span><span class="lines">@@ -134,7 +135,6 @@
</span><span class="cx">     LinkRelAttribute m_relAttribute;
</span><span class="cx">     bool m_loading;
</span><span class="cx">     bool m_createdByParser;
</span><del>-    bool m_isInShadowTree;
</del><span class="cx">     bool m_firedLoad;
</span><span class="cx">     bool m_loadedResource;
</span><span class="cx"> 
</span></span></pre></div>
<a id="trunkSourceWebCorehtmlHTMLStyleElementcpp"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebCore/html/HTMLStyleElement.cpp (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebCore/html/HTMLStyleElement.cpp        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/Source/WebCore/html/HTMLStyleElement.cpp        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -94,18 +94,17 @@
</span><span class="cx"> 
</span><span class="cx"> Node::InsertionNotificationRequest HTMLStyleElement::insertedInto(ContainerNode&amp; insertionPoint)
</span><span class="cx"> {
</span><del>-    HTMLElement::insertedInto(insertionPoint);
-    if (insertionPoint.inDocument())
</del><ins>+    bool wasInDocument = inDocument();
+    auto result = HTMLElement::insertedInto(insertionPoint);
+    if (insertionPoint.inDocument() &amp;&amp; !wasInDocument)
</ins><span class="cx">         m_styleSheetOwner.insertedIntoDocument(*this);
</span><del>-
-    return InsertionDone;
</del><ins>+    return result;
</ins><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void HTMLStyleElement::removedFrom(ContainerNode&amp; insertionPoint)
</span><span class="cx"> {
</span><span class="cx">     HTMLElement::removedFrom(insertionPoint);
</span><del>-
-    if (insertionPoint.inDocument())
</del><ins>+    if (insertionPoint.inDocument() &amp;&amp; !inDocument())
</ins><span class="cx">         m_styleSheetOwner.removedFromDocument(*this);
</span><span class="cx"> }
</span><span class="cx"> 
</span></span></pre></div>
<a id="trunkSourceWebCoresvgSVGStyleElementcpp"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebCore/svg/SVGStyleElement.cpp (208402 => 208403)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebCore/svg/SVGStyleElement.cpp        2016-11-04 22:53:21 UTC (rev 208402)
+++ trunk/Source/WebCore/svg/SVGStyleElement.cpp        2016-11-04 22:53:33 UTC (rev 208403)
</span><span class="lines">@@ -116,16 +116,17 @@
</span><span class="cx"> 
</span><span class="cx"> Node::InsertionNotificationRequest SVGStyleElement::insertedInto(ContainerNode&amp; rootParent)
</span><span class="cx"> {
</span><del>-    SVGElement::insertedInto(rootParent);
-    if (rootParent.inDocument())
</del><ins>+    bool wasInDocument = inDocument();
+    auto result = SVGElement::insertedInto(rootParent);
+    if (rootParent.inDocument() &amp;&amp; !wasInDocument)
</ins><span class="cx">         m_styleSheetOwner.insertedIntoDocument(*this);
</span><del>-    return InsertionDone;
</del><ins>+    return result;
</ins><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void SVGStyleElement::removedFrom(ContainerNode&amp; rootParent)
</span><span class="cx"> {
</span><span class="cx">     SVGElement::removedFrom(rootParent);
</span><del>-    if (rootParent.inDocument())
</del><ins>+    if (rootParent.inDocument() &amp;&amp; !inDocument())
</ins><span class="cx">         m_styleSheetOwner.removedFromDocument(*this);
</span><span class="cx"> }
</span><span class="cx"> 
</span></span></pre>
</div>
</div>

</body>
</html>