<pre class='metadata'>
Title: CSS Shadow Module Level 1
Level: 1
Shortname: css-shadow
Group: CSSWG
Status: ED
Work Status: Exploring
ED: https://drafts.csswg.org/css-shadow-1/
Previous Version: https://www.w3.org/TR/2014/WD-css-scoping-1-20140403/
Editor: Tab Atkins Jr., Google, http://xanthir.com/contact/, w3cid 42199
Editor: Fergal Daly, Google, fergal@chromium.org, w3cid 106713
Abstract: This module defines ways for CSS to interact with Shadow DOM and its scoping mechanism.
Ignored Terms: inherit, slot, custom elements, stylesheets
Ignored Vars: root elements
WPT Path Prefix: css/css-scoping/
WPT Display: closed
</pre>

<pre class="link-defaults">
spec:cascade-4; type:dfn; text: inherit
spec:css-color-5; type:function; text:color()
spec:css-pseudo-4; type:selector;
	text:::after
	text:::before
spec:css-fonts-4; type:property; text:font-family
spec:dom; type:dfn;
	text:child
	text:children
	text:descendant
	text:element; for:/
	text:find flattened slottables
	text:find slottables
	text:host
	text:root; for:tree
	text:shadow root; for:/
spec:html; type:element;
	text:style
spec:infra; type:dfn;
	text:string
	text:list
spec:selectors-4;
	type:selector; text::hover
	type:dfn;
		text:dynamic profile
		text:static profile
		text:type selector
</pre>

Introduction {#intro}
=====================

Shadow DOM allows authors to separate their page into "components",
subtrees of markup whose details are only relevant to the component itself,
not the outside page.
This reduces the chance of a style meant for one part of the page
accidentally over-applying and making a different part of the page look wrong.
However, this styling barrier also makes it harder for a page to interact with its components
when it actually <em>wants</em> to do so.

This specification defines the ''::part()'' pseudo-element,
which allows an author to style specific, purposely exposed elements in a <a>shadow tree</a>
from the outside page's context.
In combination with <a>custom properties</a>,
which let the outside page pass particular values
(such as theme colors)
into the component for it to do with as it will,
these pseudo-elements allow components and the outside page
to interact in safe, powerful ways,
maintaining encapsulation
without surrendering all control.

The '':host'' pseudo-class and its [=functional pseudo-class|functional counterpart=] '':host()'' match the [=shadow tree's=] [=shadow host=].

Furthermore, the ''::slotted'' [=pseudo-element=] and the related '':has-slotted'' [=pseudo-class=] provide ways to interact with [=slots=] and their assigned [=shadow tree=].

<wpt pathprefix="/css/css-shadow-parts/" title="General tests for shadow parts">
	all-hosts.html
	animation-part.html
	chaining-invalid-selector.html
	complex-matching.html
	complex-non-matching.html
	different-host.html
	double-forward.html
	grouping-with-checked.html
	grouping-with-disabled.html
	host-stylesheet.html
	inner-host.html
	interaction-with-nested-pseudo-class.html
	interaction-with-placeholder.html
	interaction-with-pseudo-elements.html
	invalidation-complex-selector-forward.html
	invalidation-complex-selector.html
	invalidation-part-pseudo.html
	multiple-parts.html
	part-after-combinator-invalidation.html
	part-mutation-pseudo.html
	part-nested-pseudo.html
	precedence-part-vs-part.html
	pseudo-classes-after-part.html
	pseudo-elements-after-part.html
	serialization.html
	simple-forward-shorthand.html
	simple-forward.html
	simple-important.html
	simple-important-important.html
	simple-important-inline.html
	simple.html
	simple-important.html
	simple-inline.html
	style-sharing.html
</wpt>

Note: This specification was originally titled CSS Scoping Module Level 1.
It has since been merged with CSS Shadow Parts Module Level 1 and renamed to CSS Shadow Module Level 1
to better reflect its comprehensive coverage of Shadow DOM features.
The [=scoped style rules=] feature initially described in this module has been moved to [[css-cascade-6]].


<!--
████████  ████████ ████████    ███    ██     ██ ██       ████████
██     ██ ██       ██         ██ ██   ██     ██ ██          ██
██     ██ ██       ██        ██   ██  ██     ██ ██          ██
██     ██ ██████   ██████   ██     ██ ██     ██ ██          ██
██     ██ ██       ██       █████████ ██     ██ ██          ██
██     ██ ██       ██       ██     ██ ██     ██ ██          ██
████████  ████████ ██       ██     ██  ███████  ████████    ██
-->

Default Styles for Custom Elements {#default-element-styles}
============================================================

	Advisement: This section is <strong>experimental</strong>,
	and is under active discussion.
	Do not implement without consulting the CSSWG.

	When defining <a>custom elements</a>,
	one often wants to set up "default" styles for them,
	akin to the user-agent styles that apply to built-in elements.
	This is, unfortunately, hard to do in vanilla CSS,
	due to issues of scoping and specificity--
	the element in question might be used in <a>shadow trees</a>,
	and thus is unreachable by any selector targeting it in the outermost document;
	and selectors, even low-specificity ones like simple <a>type selectors</a>,
	can accidentally override author-level styles meant to target the element.

	To aid in this, this section defines a way
	to create a stylesheet of "default element styles" for a given element.
	This stylesheet applies across the entire document,
	in all <a>shadow trees</a>,
	and the rules in it apply at the <a>user-agent origin</a>,
	so author-level rules automatically win.

	{{Window}}s gain a private slot <dfn attribute for=Window>\[[defaultElementStylesMap]]</dfn>
	which is a map of <a for="Element">local names</a> to <a>stylesheets</a>.

	These stylesheets must apply to every document in the window.
	They must be interpreted as user agent stylesheets.

	Note: This implies, in particular,
	that they apply to all <a>shadow trees</a> in every document,
	and that the declarations in them are from the <a>user-agent origin</a>.

	For the purpose of the <a>cascade</a>,
	these stylesheets are ordered after the user agent's own stylesheets;
	their relative ordering doesn't matter as it is not observable.

	Within these stylesheets, <a>complex selectors</a> must be treated as invalid.
	Every <a>compound selector</a> must be treated as containing an additional <a>type selector</a>
	that selects elements with the <a for=Element>local name</a>
	that the stylesheet is keyed with.

	Issue: Do we need to restrict the <a>at-rules</a> that can be used in these sheets?
	For example, do we allow an ''@font-face''?
	I'm going to leave it as allowed unless/until I hear complaints.

	This specification does not define how to add to, remove from, or generally manipulate
	the {{[[defaultElementStylesMap]]}}.
	It is expected that other specifications,
	such as [[DOM]],
	will define ways to do so.

<!--
 ██████  ██     ██    ███    ████████   ███████  ██      ██
██    ██ ██     ██   ██ ██   ██     ██ ██     ██ ██  ██  ██
██       ██     ██  ██   ██  ██     ██ ██     ██ ██  ██  ██
 ██████  █████████ ██     ██ ██     ██ ██     ██ ██  ██  ██
      ██ ██     ██ █████████ ██     ██ ██     ██ ██  ██  ██
██    ██ ██     ██ ██     ██ ██     ██ ██     ██ ██  ██  ██
 ██████  ██     ██ ██     ██ ████████   ███████   ███  ███
-->

Shadow Encapsulation {#shadow-dom}
==================================

Informative Explanation of Shadow DOM {#shadow-gloss}
-----------------------------------------------------

	<em>The following is a non-normative explanation
	of several concepts normatively defined in the DOM Standard [[!DOM]],
	to aid in understanding what this spec defines
	without having to fully grok the DOM Standard.</em>

	In addition to the qualities of an element tree defined in [[SELECTORS4#data-model]],
	the DOM Standard adds several new concepts related to <a>shadow trees</a>,
	several of which are relevant to CSS.

	An element can host a <a>shadow tree</a>,
	which is a special kind of document fragment
	with a <a>shadow root</a>
	(a non-element node)
	at its root.
	Children of the <a>shadow root</a> are ordinary elements and other nodes.
	The element hosting the <a>shadow tree</a> is its <a>host</a>,
	or <a>shadow host</a>.

	The elements in a <a>shadow tree</a> are not <a>descendants</a> of the <a>shadow host</a> in general
	(including for the purposes of Selectors like the <a>descendant combinator</a>).
	However, the <a>shadow tree</a>,
	when it exists,
	is used in the construction of the <a>flattened element tree</a>,
	which CSS uses for all purposes <em>after</em> Selectors
	(including inheritance and box construction).

	Loosely, the <a>shadow tree</a> is treated as the <a>shadow host's</a> contents
	instead of its normal <a>light tree</a> contents.
	However, some of its <a>light tree</a> children
	can be "pulled into" the <a>shadow tree</a>
	by assigning them to <a>slots</a>.
	This causes them to be treated as children of the <a>slot</a>
	for CSS purposes.
	The <a>slots</a> can then be assigned to <a>slots</a>
	in deeper <a>shadow trees</a>;
	luckily, <a>slots</a> themselves don't generate boxes by default,
	so you don't get an unpredictable cascade of <{slot}> wrapper elements
	disrupting your CSS.

	If nothing is explicitly assigned to a <a>slot</a>,
	the <a>slot's</a> own children are instead assigned to it,
	as a sort of "default" contents.

Shadow DOM and Selectors {#selectors}
-------------------------------------

<h4 id='selectors-data-model'>
Matching Selectors Against Shadow Trees</h4>

	When a selector is matched against a <a>shadow tree</a>,
	the selector match list
	is initially the <a>shadow host</a>,
	followed by all children of the <a>shadow tree's</a> <a>shadow root</a>
	and their descendants,
	ordered by a pre-order traversal.

	Issue: Rewrite this against the newer call forms of the matching algorithms.

	Note: Remember that the <a>descendants</a> of an element
	are based on the <a>light tree</a> <a>children</a> of the element,
	which does not include the <a>shadow trees</a> of the element.

	When a selector is <a lt="match a selector against a tree">matched against a tree</a>,
	its <dfn export>tree context</dfn> is the <a>root</a> of the <var>root elements</var> passed to the algorithm.
	If the <a>tree context</a> is a <a>shadow root</a>,
	that selector is being matched <dfn export lt="in the context of a shadow tree|in the context of the shadow tree">in the context of a shadow tree</dfn>.

	<div class="example">
		For example,
		any selector in a stylesheet embedded in or linked from an element in a <a>shadow tree</a>
		is <a>in the context of a shadow tree</a>.
		So is the argument to {{querySelector()}} when called from a <a>shadow root</a>.
	</div>

	Declarations inherit the <a>tree context</a>
	of the selector that was matched to apply them.

<wpt>
	css-scoping-shadow-assigned-node-with-before-after.html
	css-scoping-shadow-dynamic-remove-style-detached.html
	css-scoping-shadow-assigned-node-with-rules.html
	css-scoping-shadow-host-with-before-after.html
	css-scoping-shadow-invisible-slot.html
	css-scoping-shadow-root-hides-children.html
	css-scoping-shadow-slot-display-override.html
	css-scoping-shadow-slot-fallback.html
	css-scoping-shadow-slot.html
	css-scoping-shadow-slot-style.html
	css-scoping-shadow-with-outside-rules.html
	css-scoping-shadow-with-rules.html
	css-scoping-shadow-with-rules-no-style-leak.html
	keyframes-001.html
	keyframes-002.html
	shadow-assign-dynamic-001.html
	shadow-disabled-sheet-001.html
	shadow-fallback-dynamic-001.html
	shadow-fallback-dynamic-002.html
	shadow-fallback-dynamic-003.html
	shadow-fallback-dynamic-004.html
	shadow-fallback-dynamic-005.html
	shadow-host-with-before-after.html
	shadow-link-rel-stylesheet-no-style-leak.html
	shadow-multiple-links.html
	shadow-reassign-dynamic-001.html
	shadow-reassign-dynamic-002.html
	shadow-reassign-dynamic-004.html
	shadow-reassign-dynamic-005-crash.html
	shadow-reassign-dynamic-006.html
	shadow-root-insert-into-document.html
	slotted-text-with-flex.html
	whitespace-crash-001.html
</wpt>

<h4 id='host-element-in-tree'>
Selecting Shadow Hosts from within a Shadow Tree</h4>

	A <a>shadow host</a> is outside of the <a>shadow tree</a> it hosts,
	and so would ordinarily be untargettable by any selectors evaluated <a>in the context of the shadow tree</a>
	(as selectors are limited to a single tree),
	but it is sometimes useful to be able to style it from inside the <a>shadow tree</a> context.

	For the purpose of Selectors,
	a <a>shadow host</a> also appears in its <a>shadow tree</a>,
	with the contents of the <a>shadow tree</a> treated as its children.
	(In other words, the <a>shadow host</a> is treated as replacing the <a>shadow root</a> node.)

	When considered within its own <a>shadow trees</a>,
	the <a>shadow host</a> is <a>featureless</a>.
	Only the '':host'', '':host()'', and '':host-context()'' pseudo-classes are allowed to match it.

	<wpt>
		host-descendant-003.html
		host-is-006.html
		host-is-featureless.html
		host-multiple-002.html
		host-multiple-003.html
		host-multiple-004.html
		host-multiple-005.html
		host-not-001.html
	</wpt>

	<details class='note'>
		<summary>Why is the shadow host so weird?</summary>

		The <a>shadow host</a> lives outside the <a>shadow tree</a>,
		and its markup is in control of the page author,
		not the component author.

		It would not be very good if a component used a particular class name
		internally in a <a>shadow tree</a> stylesheet,
		and the page author using the component accidentally <em>also</em>
		used the same class name and put it on the <a>shadow host</a>.
		Such a situation would result in accidental styling
		that is impossible for the component author to predict,
		and confusing for the page author to debug.

		However, there are still some reasonable use-cases for letting a stylesheet in a <a>shadow tree</a>
		style its <a>shadow host</a>.
		(For example,
		the component might want to be laid out as a flexbox,
		requiring the <a>shadow host</a> to be set to ''display: flex''.)
		So, to allow this situation but prevent accidental styling,
		the <a>shadow host</a> appears but is completely featureless
		and unselectable except through '':host'' and its related functional forms,
		which make it very explicit when you're trying to match against markup provided by the page author.
	</details>

<wpt>
	host-with-default-namespace-001.html
	host-context-parsing.html
	host-defined.html
	host-is-001.html
	host-is-002.html
	host-is-003.html
	host-is-004.html
	host-is-005.html
	host-parsing.html
	scope-pseudo-in-shadow.html
</wpt>

<!--
 ██  ██     ██  ███████   ██████  ████████
████ ██     ██ ██     ██ ██    ██    ██
 ██  ██     ██ ██     ██ ██          ██
     █████████ ██     ██  ██████     ██
 ██  ██     ██ ██     ██       ██    ██
████ ██     ██ ██     ██ ██    ██    ██
 ██  ██     ██  ███████   ██████     ██
-->

<h4 id='host-selector'>
Selecting Into the Light: the '':host'', '':host()'', and '':host-context()'' pseudo-classes</h4>

	The <dfn selector>:host</dfn> pseudo-class,
	when evaluated <a>in the context of a shadow tree</a>,
	matches the <a>shadow tree's</a> <a>shadow host</a>.
	In any other context,
	it matches nothing.

	The <dfn selector id="selectordef-host-function">:host()</dfn> function pseudo-class
	has the syntax:

	<pre>:host( <<compound-selector>> )</pre>

	When evaluated <a>in the context of a shadow tree</a>,
	it matches the <a>shadow tree's</a> <a>shadow host</a>
	if the <a>shadow host</a>,
	in its normal context,
	matches the selector argument.
	In any other context,
	it matches nothing.

	The [=specificity=] of '':host'' is that of a pseudo-class.
	The [=specificity=] of '':host()'' is that of a pseudo-class,
	plus the [=specificity=] of its argument.

	Note: This is different from the specificity of similar pseudo-classes,
	like '':is()'' or '':not()'',
	which <em>only</em> take the specificity of their argument.
	This is because '':host'' is affirmatively selecting an element all by itself,
	like a "normal" pseudo-class;
	it takes a selector argument for syntactic reasons
	(we can't say that '':host.foo'' matches but ''.foo'' doesn't),
	but is otherwise identical
	to just using '':host'' followed by a selector.

	<div class='example'>
		For example, say you had a component with a <a>shadow tree</a> like the following:

		<pre>
			&lt;x-foo class="foo">
				&lt;"shadow tree">
					&lt;div class="foo">...&lt;/div>
				&lt;/>
			&lt;/x-foo>
		</pre>

		For a stylesheet within the <a>shadow tree</a>:

		* '':host'' matches the <code>&lt;x-foo></code> element.
		* ''x-foo'' matches nothing.
		* ''.foo'' matches only the <code>&lt;div></code> element.
		* ''.foo:host'' matches nothing
		* '':host(.foo)'' matches the <code>&lt;x-foo></code> element.
	</div>

	Ordinary, selectors within a <a>shadow tree</a>
	can't see elements outside the <a>shadow tree</a> at all.
	Sometimes, however, it's useful to select an ancestor that lies somewhere outside the shadow tree,
	above it in the document.

	<div class='example'>
		For example, a group of components can define a handful of color themes
		they know how to respond to.
		Page authors could opt into a particular theme
		by adding a specific class to the components,
		or higher up in the document.
	</div>

	The <dfn selector>:host-context()</dfn> functional pseudo-class tests whether there is an ancestor,
	outside the <a>shadow tree</a>,
	which matches a particular selector.
	Its syntax is:

	<pre class=prod>:host-context( <<compound-selector>> )</pre>

	When evaluated <a>in the context of a shadow tree</a>,
	the '':host-context()'' pseudo-class matches the <a>shadow host</a>,
	if the <a>shadow host</a> or one of its <a>shadow-including ancestors</a>
	matches the provided <<compound-selector>>.
	In any other context,
	it matches nothing.

	The [=specificity=] of '':host-context()'' is that of a pseudo-class,
	plus the [=specificity=] of its argument.

	Note: This means that the selector pierces through shadow boundaries on the way up,
	looking for elements that match its argument,
	until it reaches the document root.

<wpt>
	css-scoping-shadow-host-functional-rule.html
	css-scoping-shadow-host-namespace.html
	css-scoping-shadow-host-rule.html
	host-context-specificity-001.html
	host-context-specificity-002.html
	host-context-specificity-003.html
	host-descendant-001.html
	host-descendant-002.html
	host-descendant-invalidation.html
	host-dom-001.html
	host-functional-descendant-invalidation.html
	host-has-internal-001.html
	host-has-internal-002.html
	host-has-internal-003.html
	host-has-internal-004.html
	host-in-host-context-selector.html
	host-in-host-selector.html
	host-multiple-001.html
	host-nested-001.html
	host-slotted-001.html
	host-specificity-002.html
	host-specificity-003.html
	host-specificity.html
	shadow-host-removal-invalidation.html
	shadow-at-import.html
	shadow-host-style-sharing.html
	shadow-link-rel-stylesheet.html
	shadow-shared-style-cache-001.html
	stylesheet-title-001.html
	stylesheet-title-002.html
</wpt>


<!--
 ██   ██   ██████  ██        ███████  ████████ ████████ ████████ ████████
████ ████ ██    ██ ██       ██     ██    ██       ██    ██       ██     ██
 ██   ██  ██       ██       ██     ██    ██       ██    ██       ██     ██
           ██████  ██       ██     ██    ██       ██    ██████   ██     ██
 ██   ██        ██ ██       ██     ██    ██       ██    ██       ██     ██
████ ████ ██    ██ ██       ██     ██    ██       ██    ██       ██     ██
 ██   ██   ██████  ████████  ███████     ██       ██    ████████ ████████
-->

<h4 id='slotted-pseudo'>
Selecting Slot-Assigned Content: the ''::slotted()'' pseudo-element</h4>

	The <dfn selector>::slotted()</dfn> pseudo-element
	represents the elements <a lt="find flattened slottables">assigned, after flattening,</a> to a <a>slot</a>.
	This pseudo-element only exists on <a>slots</a>.

	The ''::slotted()'' pseudo-element is an <em>alias</em> for other elements in the tree,
	and does not generate any boxes itself.

	The grammar of the ''::slotted()'' pseudo-element is:

	<pre class=prod>::slotted( <<compound-selector>> )</pre>

	The ''::slotted()'' pseudo-element represents the elements that are:

	* <a lt="find flattened slottables">assigned, after flattening,</a> to the <a>slot</a> that is ''::slotted''’s originating element
	* <a lt="match a selector against an element">matched</a> by its <<compound-selector>> argument

	<wpt>
		slotted-has-001.html
		slotted-has-002.html
		slotted-has-003.html
		slotted-has-004.html
	</wpt>

	The ''::slotted()'' pseudo-element can be followed by a <a>tree-abiding pseudo-element</a>,
	like ''::slotted()::before'',
	representing the appropriate pseudo-element of the elements represented by the ''::slotted()'' pseudo-element.

	<wpt>
		slotted-details-content.html
		slotted-file-selector-button.html
	</wpt>

	The [=specificity=] of ''::slotted()'' is that of a pseudo-element,
	plus the [=specificity=] of its argument.

	<div class="example">
		For example, say you had a component with both children and a shadow tree,
		like the following:

		<pre>
			&lt;x-foo>
				&lt;div id="one" slot="foo" class="foo">...&lt;/div>
				&lt;div id="two" slot="foo">...&lt;/div>
				&lt;div id="three" class="foo">
					&lt;div id="four" slot="foo">...&lt;/div>
				&lt;/div>
				&lt;"shadow tree">
					&lt;div id="five">...&lt;/div>
					&lt;div id="six">...&lt;/div>
					&lt;slot name="foo">&lt;/slot>
				&lt;/"shadow tree">
			&lt;/x-foo>
		</pre>

		For a stylesheet within the <a>shadow tree</a>,
		a selector like ''::slotted(*)''
		selects ''#one'' and ''#two'' only,
		as they're the elements <a lt="find flattened slottables">assigned</a> to the sole <{slot}> element.
		It will <em>not</em> select ''#three''
		(no <code>slot</code> attribute)
		nor ''#four''
		(only direct <a>children</a> of a <a>shadow host</a> can be assigned to a <a>slot</a>).

		A selector like ''::slotted(.foo)'',
		on the other hand,
		will only select ''#one'',
		as it matches ''.foo'',
		but ''#two'' doesn't.

		Note: Note that a selector like ''::slotted(*)''
		is equivalent to ''*::slotted(*)'',
		where the ''*'' selects many more elements than just the <{slot}> element.
		However, since only the <{slot}> elements are <a>slots</a>,
		they're the only elements with a ''::slotted()'' pseudo-element as well.
	</div>

	Note: ''::slotted()'' can only represent the <em>elements</em>
	assigned to the <a>slot</a>.
	<a>Slots</a> can also be assigned text nodes,
	which can't be selected by ''::slotted()''.
	The only way to style assigned text nodes
	is by styling the <a>slot</a> and relying on inheritance.

<wpt>
	css-scoping-shadow-slotted-nested.html
	css-scoping-shadow-slotted-rule.html
	reslot-text-inheritance.html
	slotted-invalidation.html
	slotted-link.html
	slotted-matches.html
	slotted-nested.html
	slotted-parsing.html
	slotted-placeholder.html
	slotted-slot.html
	slotted-specificity-002.html
	slotted-specificity.html
	slotted-with-pseudo-element.html
</wpt>

<h4 id='the-has-slotted-pseudo'>
Matching on the Presence of Slot-Assigned Nodes: the '':has-slotted'' pseudo-class</h4>

	The <dfn selector>:has-slotted</dfn> pseudo-class
	matches <{slot}> elements
	which have a non-empty list of <a lt="find flattened slottables">flattened slotted nodes</a>.

	When '':has-slotted'' matches a slot with fallback content,
	we can conclude that the fallback content is <em>not</em> being displayed.

	Note: Even a single whitespace text node is sufficient to make '':has-slotted''' apply.
	This is by design, so that the behavior of this pseudo-class is consistent with the behavior of the {{HTMLSlotElement/assignedNodes()}} method.
	A future version of this specification is expected to introduce a way to exclude this case from matching.

	Note: It is expected that a future version of this specification will introduce a functional '':has-slotted()'' pseudo-class that allows
	more fine-grained matching by accepting a selector argument.
	'':has-slotted'' is <em>not</em> an alias of '':has-slotted(*)'',
	as the latter would not match slotted text nodes, but '':has-slotted'' does.

<wpt>
	has-slotted-001.html
	has-slotted-002.html
	has-slotted-003.html
	has-slotted-changing-001.html
	has-slotted-changing-002.html
	has-slotted-flattened-001.html
	has-slotted-flattened-002.html
	has-slotted-flattened-003.html
	has-slotted-flattened-004.html
	has-slotted-manual-assignment.html
	has-slotted-query-selector.html
</wpt>

<!--
 ██████     ███     ██████   ██████     ███    ████████  ████████
██    ██   ██ ██   ██    ██ ██    ██   ██ ██   ██     ██ ██
██        ██   ██  ██       ██        ██   ██  ██     ██ ██
██       ██     ██  ██████  ██       ██     ██ ██     ██ ██████
██       █████████       ██ ██       █████████ ██     ██ ██
██    ██ ██     ██ ██    ██ ██    ██ ██     ██ ██     ██ ██
 ██████  ██     ██  ██████   ██████  ██     ██ ████████  ████████
-->

Shadow Trees and the Cascade {#shadow-cascading}
================================================

	See [[css-cascade-4#cascade-sort]].

<wpt>
	shadow-cascade-order-001.html
</wpt>

<!--
████████ ██          ███    ████████       ████████ ████████  ████████ ████████
██       ██         ██ ██      ██             ██    ██     ██ ██       ██
██       ██        ██   ██     ██             ██    ██     ██ ██       ██
██████   ██       ██     ██    ██             ██    ████████  ██████   ██████
██       ██       █████████    ██             ██    ██   ██   ██       ██
██       ██       ██     ██    ██             ██    ██    ██  ██       ██
██       ████████ ██     ██    ██             ██    ██     ██ ████████ ████████
-->

<h3 id='flattening' algorithm>
Flattening the DOM into an Element Tree</h3>

	While Selectors operates on the DOM tree as the host language presents it,
	with separate trees that are unreachable via the standard parent/<a>child</a> relationship,
	the rest of CSS needs a single unified tree structure to work with.
	This is called the <dfn export lt="flat tree|flattened element tree">flattened element tree</dfn>
	(or <a>flat tree</a>),
	and is constructed as follows:

	1. Let <var>pending nodes</var> be a list of DOM nodes with associated parents,
		initially containing just the document's <a>root</a> element with no associated parent.
	2. Repeatedly execute the following substeps until <var>pending nodes</var> is empty:
		1. Pop the first element from <var>pending nodes</var>,
			and assign it to <var>pending node</var>.
		2. Insert <var>pending node</var> into the <a>flat tree</a>
			as a child of its associated parent.
			(If it has no associated parent,
			it's the document root--
			just insert it into the <a>flat tree</a> as its root.)
		3. Perform one of the following,
			whichever is the first that matches:

			<dl class=switch>
				<dt><var>pending node</var> is a <a>shadow host</a>
				<dd>
					Append the child nodes of the <a>shadow root</a> of the <a>shadow tree</a> it hosts
					to <var>pending nodes</var>,
					with <var>pending node</var> as their associated parent.
				<dt><var>pending node</var> is a <a>slot</a>
				<dd>
					<a>Find slottables</a> for <var>pending node</var>,
					and append them to <var>pending nodes</var>,
					with <var>pending node</var> as their associated parent.

					If no <a>slottables</a> were found for <var>pending node</var>,
					instead append its <a>children</a> to <var>pending nodes</var>,
					with <var>pending node</var> as their associated parent.
				<dt>Otherwise,
				<dd>
					Append the child nodes of <var>pending node</var>’s <a>light tree</a>
					to <var>pending nodes</var>,
					with <var>pending node</var> as their associated parent.
			</dl>

	Note: In other words, the <a>flat tree</a> is the top-level DOM tree,
	but <a>shadow hosts</a> are filled with their <a>shadow tree</a> children
	instead of their <a>light tree</a> children
	(and this proceeds recursively if the <a>shadow tree</a> contains any <a>shadow hosts</a>),
	and <a>slots</a> get filled with the nodes that are assigned to them
	(and this proceeds recursively if the <a>slots</a> are themselves
	assigned to a <a>slot</a> in a deeper <a>shadow tree</a>).

	Issue: A non-obvious result of this
	is that elements assigned to a slot inherit from that slot,
	not their light-tree parent
	or any deeper slots their slot gets assigned to.
	This means that text nodes are styled by the shadow tree of their parent,
	with nobody else capable of intervening in any way.
	Do we want an additional pseudo-element for targeting those text nodes
	so they can be styled at all slot-assignment levels,
	like normal elements can be?
	This implies it needs to work for text nodes in the light tree
	before they're assigned downwards,
	so this can't just be a ''::slotted()'' variant.
	Luckily, this is a long-standing request!

<h4 id='slots-in-shadow-tree'>
Slots and Slotted Elements in a Shadow Tree</h4>

	<a>Slots</a> must act as if they were assigned ''display: contents''
	via a rule in the <a>UA origin</a>.
	This must be possible to override via 'display',
	so they <em>do</em> generate boxes if desired.

	Note: A non-obvious result of assigning elements to <a>slots</a>
	is that they <a>inherit</a> from the <a>slot</a> they're assigned to.
	Their original <a>light tree</a> parent,
	and any deeper <a>slots</a> that their <a>slot</a> gets assigned to,
	don't affect inheritance.

<wpt>
	css-scoping-shadow-nested-slot-display-override.html
	shadow-reassign-dynamic-003.html
	slot-non-html-display-value.html
</wpt>

<!--
████████ ████████  ████████ ████████          ██████   ██████   ███████  ████████  ████████ ████████
   ██    ██     ██ ██       ██               ██    ██ ██    ██ ██     ██ ██     ██ ██       ██     ██
   ██    ██     ██ ██       ██               ██       ██       ██     ██ ██     ██ ██       ██     ██
   ██    ████████  ██████   ██████   ███████  ██████  ██       ██     ██ ████████  ██████   ██     ██
   ██    ██   ██   ██       ██                     ██ ██       ██     ██ ██        ██       ██     ██
   ██    ██    ██  ██       ██               ██    ██ ██    ██ ██     ██ ██        ██       ██     ██
   ██    ██     ██ ████████ ████████          ██████   ██████   ███████  ██        ████████ ████████
-->

<h3 id='shadow-names'>
Name-Defining Constructs and Inheritance</h3>

	[=Shadow trees=] are meant to be an encapsulation boundary,
	allowing independent authors to share code
	without accidentally polluting each other's namespaces.
	For example, element IDs,
	which are generally meant to be unique within a document,
	can be validly used multiple times
	as long as each use is in a different [=shadow tree=].

	Similarly, several [=at-rules=] in CSS,
	such as ''@keyframes'' or ''@font-face'',
	define a name that later at-rules or properties can refer to them by.
	Like IDs, these names are globally exposed and unique within a document;
	also like IDs,
	this restriction is now loosened to being unique within a given [=shadow tree=].

	However, property inheritance can carry values from one tree to another,
	which complicates referencing the correct definition of a given name.
	Done naively, this can produce surprising and confusing results for authors.
	This section defines a set of concepts to use in defining and referencing "global" names
	in a way that respects encapsulation
	and doesn't give surprising results.

	If an at-rule or property defines a name that other CSS constructs can refer to it by,
	such as a ''@font-face'' '@font-face/font-family!!descriptor' name
	or an 'anchor-scope' name,
	it must be defined as a <dfn export for=CSS>tree-scoped name</dfn>.
	[=Tree-scoped names=] are associated with
	the [=root=] of the [=element=] hosting the stylesheet
	that the at-rule or property is declared in.

	Additionally, [=tree-scoped names=] can be
	<dfn export for="tree-scoped name, tree-scoped reference" lt="loosely matched | loosely-matched">loosely matched</dfn> or
	<dfn export for="tree-scoped name, tree-scoped reference" lt="strictly  matched | strictly-matched">strictly matched</dfn>,
	defaulting to [=loosely matched=] unless otherwise specified.
	A [=loosely matched=] [=tree-scoped name=]
	can be matched by [=tree-scoped references=]
	(see below)
	in the same tree or descendant trees,
	while a [=strictly matched=] [=tree-scoped name=]
	can only be matched by [=tree-scoped references=]
	in the exact same tree.

	Properties or descriptors that reference a [=tree-scoped name=],
	such as the 'font-family!!property'
	or 'animation-name' properties,
	must define their value as a <dfn export for=CSS>tree-scoped reference</dfn>.
	These references implicitly capture
	a [=node tree=] [=root=]
	along with their specified value:
	unless otherwise specified,
	the [=root=] of the [=element=] hosting the stylesheet that the property or descriptor is declared in.
	This [=root=] reference stays with the [=tree-scoped reference=]
	as it is inherited.

	<wpt>
		svg-id-ref-001.html
	</wpt>

	If a [=tree-scoped name=] is <dfn export for="tree-scoped name">global</dfn>
	(such as ''@font-face'' names),
	then when a [=tree-scoped reference=] is dereferenced to find it,
	first search only the [=tree-scoped names=] associated with the same [=root=]
	as the [=tree-scoped reference=].
	If no relevant [=tree-scoped name=] is found,
	and the [=root=] is a [=shadow root=],
	then repeat this search in the [=root=]'s [=host=]'s [=node tree=] (recursively).
	(In other words, global [=tree-scoped names=] “inherit” into descendant shadow trees,
	so long as they don't define the same name themselves.)

	If a [=tree-scoped name=] is <dfn export for="tree-scoped name">local</dfn> to an element
	(such as 'anchor-name' or 'anchor-scope' values),
	then whether a [=tree-scoped reference=] matches the [=tree-scoped name=] on a given element
	depends on whether the [=tree-scoped name=] is [=tree-scoped name/strictly matched|strictly=] or [=tree-scoped name/loosely matched|loosely=] matched.
	A [=tree-scoped name/strictly matched=] [=tree-scoped name=] only matches if
	both names are associated with the same tree.
	A [=tree-scoped name/loosely matched=] [=tree-scoped name=] also matches if
	the [=tree-scoped name=] is associated with an ancestor tree.

	If two [=tree-scoped names=] are directly compared
	(for example, when comparing [=computed values=]),
	they are considered to match only if their identifiers match,
	<em>and</em> their [=root=]s match exactly.
	(If one has a [=root=] that's an ancestor of the other, for example,
	they <em>do not</em> match.)

	<div class=issue>
		TODO: Fix all the at-rules that define global names,
		and the properties that reference them,
		to use these concepts.

		Global names include:

		* ''@font-face'', referenced by 'font-family!!property'
		* ''@font-feature-values'', referenced by 'font-family!!property'
		* ''@keyframes'', referenced by 'animation-name'
		* ''@counter-style'', referenced by 'list-style-type'
		* ''@color-profile'', referenced by the ''color()'' function
		* ''@font-palette-values'', referenced by 'font-palette'
		* others?
	</div>

	<div class=example>

		For example,
		given the following document
		(using the imaginary &lt;::shadow>&lt;/::shadow> markup
		to indicate an element's [=shadow tree=]):

		<xmp highlight=markup>
			<p class=outer>Here's some text in the outer document's "foo" font.
			<style>
				@font-face {
					font-family: foo;
					src: url(https://example.com/outer.woff);
				}
				body { font-family: foo; }
				my-component::part(text) { font-family: foo; }
			</style>

			<my-component>
				<::shadow>
					<p class=inner-default>I'm inheriting the outer document's font-family.
					<p class=inner-styled>And I'm explicitly styled to be in the component's "foo" font.
					<p class=part-styled part=text>
						I'm explicitly styled by the outer document,
						and get the outer document's "foo" font.
					<style>
						@font-face {
							font-family: foo;
							src: url(https://example.com/inner.woff);
						}
						.inner-styled { font-family: foo; }
					</style>
				</::shadow>
			</my-component>
		</xmp>

		The ''.outer'' element references the outer ''@font-face'', using the "outer.woff" file.

		The ''.inner-default'' element inherits the ''font-family: foo'' value from the outer document,
		using the same [=tree-scoped reference=] as ''.outer'',
		and thus also uses the "outer.woff" font file.

		The ''.inner-style'' element, on the other hand,
		receives a ''font-family: foo'' from the stylesheet inside the shadow,
		and thus its [=tree-scoped reference=] refers to the shadow's ''@font-family'',
		and it uses the "inner.woff" file.

		The ''.part-styled'' element also receives its style from the outer document,
		tho by being directly set rather than by inheritance.
		Thus, its [=tree-scoped reference=] also refer's to the outer document,
		and it uses the "outer.woff" file.
	</div>

	<div class=example>
		Here is a more complex example,
		showing three levels of trees,
		and illustrating precisely how [=tree-scoped names=] and [=tree-scoped references=] inherit.

		<xmp highlight=markup>
			<style>
				@font-face {
					font-family: foo;
					src: url(https://example.com/outer.woff);
				}
				body { font-family: foo; }
			</style>

			<child-component>
				<::shadow>
					<style>
						@font-face {
							font-family: foo;
							src: url(https://example.com/inner.woff);
						}
					</style>

					<grandchild-component>
						<::shadow>
							<p class=inner-default>
								I'm inheriting the outer document's "foo" font.
							</p>
							<p class=inner-search>
								And I can't find a local "foo" font,
								so I'm searching further up the tree,
								and find the shadow's "foo" font.
							</p>
							<style>
							.inner-search { font-family: foo; }
							</style>
						</::shadow>
					</grandchild-component>
				</::shadow>
			</child-component>
		</xmp>

		Here, just as in the previous example,
		''.inner-default'' is inheriting the ''font-family: foo'' declared in the outer document,
		and so it ends up referencing the outer document's ''@font-face'',
		and is rendered with the "outer.woff" file.

		On the other hand,
		''.inner-search'' receives its style from a stylesheet in <code>&lt;grandchild-component></code>'s shadow tree,
		so it attempts to find a ''@font-face'' defining a ''foo'' font in that tree.
		There is no such ''@font-face'',
		so it starts walking up the shadow trees,
		finding an appropriate ''@font-face'' in <code>&lt;child-component></code>,
		so it's rendered with the "inner.woff" file.
	</div>

<wpt>
	font-face-001.html
	font-face-002.html
	font-face-003.html
	font-face-004.html
	font-face-005.html
	font-face-006.html
	font-face-007.html
	font-face-008.html
	font-face-009.html
	keyframes-003.html
	keyframes-004.html
	keyframes-005.html
	keyframes-006.html
	scoped-reference-animation-001.html
	scoped-reference-animation-002.html
</wpt>

<h4 id='shadow-names-serialization'>
Serialized Tree-Scoped References</h4>

	If a [=tree-scoped reference=] is serialized,
	it serializes only its value;
	the associated [=root=] is lost.

	<div class=example>

		This implies that `el.style.foo = getComputedStyle(el).foo;`
		is not necessarily a no-op,
		like it typically was before [=shadow trees=] existed.

		For example,
		given the following document
		(using the imaginary &lt;::shadow>&lt;/::shadow> markup
		to indicate an element's [=shadow tree=]):

		<xmp highlight=markup>
			<p class=outer>Here's some text in the outer document's "foo" font.
			<style>
				@font-face {
					font-family: foo;
					src: url(foo.woff);
				}
				body { font-family: foo; }
			</style>

			<my-component>
				<::shadow>
					<p class=inner-default>I'm inheriting the outer document's font-family.
					<p class=inner-styled>And I'm explicitly styled to be in the component's "foo" font.
					<style>
						@font-face {
							font-family: foo;
							src: url(https://example.com/foo.woff);
						}
						.inner-styled { font-family: foo; }
					</style>
					<script>
						const innerDefault = document.querySelector('.inner-default');
						const innerStyled = document.querySelector('.inner-styled');
						const defaultFont = getComputedStyle(innerDefault).fontFamily;
						const styledFont = getComputedStyle(innerStyled).fontFamily;

						console.log(defaultFont == styledFont); // true!
					</script>
				</::shadow>
			</my-component>
		</xmp>

		The <code>.outer</code> element is styled with the outer document's "foo" ''@font-face''.
		The <code>.inner-default</code> element inherits 'font-family' from the outer document,
		meaning it inherits a [=tree-scoped reference=]
		referencing that outer document,
		and so it's in the same font as <code>.outer</code>.

		Meanwhile, <code>.inner-styled</code> is explicitly styled from inside the shadow root,
		so it receives a fresh [=tree-scoped reference=]
		referencing its shadow tree,
		and it is instead styled the shadow's own "foo" ''@font-face''.

		Despite that, the script running inside the component
		sees the two elements as having the same value for 'font-family',
		because the [=root=]-reference part of a [=tree-scoped reference=]
		is not preserved by serialization.
		If it were to set <code highlight=js>innerDefault.style.fontFamily = defaultFont;</code>
		(thus setting the 'font-family' property of the element's attribute stylesheet,
		which lives in the shadow tree),
		the <code>.inner-default</code> element would suddenly switch
		to the same font as <code>.inner-styled</code>!
	</div>

	Note: The [[css-typed-om-1]] is expected to reflect the [=root=] reference of a [=tree-scoped reference=]
	in its [=reification=] rules for values,
	allowing authors to tell what [=node tree=] the reference is taking its values from,
	and allowing values to be transported across [=node trees=]
	without changing their meaning.


<!-- Big Text: parts

████▌   ███▌  ████▌  █████▌  ███▌
█▌  █▌ ▐█ ▐█  █▌  █▌   █▌   █▌  █▌
█▌  █▌ █▌  █▌ █▌  █▌   █▌   █▌
████▌  █▌  █▌ ████▌    █▌    ███▌
█▌     █████▌ █▌▐█     █▌       █▌
█▌     █▌  █▌ █▌ ▐█    █▌   █▌  █▌
█▌     █▌  █▌ █▌  █▌   █▌    ███▌
-->
Exposing a Shadow Element {#exposing}
=====================================
Elements in a <a>shadow tree</a> may be exported for styling by stylesheets outside the tree
using the part and exportparts attributes.

Each element has a <dfn export for="element">part name list</dfn>
which is an [=ordered set=] of tokens.

Each element has a <dfn export for="element">forwarded part name list</dfn>
which is a [=list=] of [=tuples=]
containing a [=string=] for the inner part being forwarded
and a [=string=] giving the name it will be exposed as.

Each <a>shadow root</a> can be thought of as having a <dfn export for="shadow root">part element map</dfn>
with keys that are [=strings=]
and values that are [=ordered sets=] of elements.

The [=part element map=] is described
only as part of the algorithm for calculating style in this spec.
It is not exposed via the DOM,
as calculating it may be expensive
and exposing it could allow access to elements inside closed shadow roots.

[=Part element maps=] are affected by the addition and removal of elements
and changes to the [=part name lists=] and [=forwarded part name lists=] of elements in the DOM.

<div algorithm>
	To <dfn>calculate the [=part element map=]</dfn> of a shadow root, |outerRoot|:

	1. For each [=descendant=] |el| within |outerRoot|:
		1. For each |name| in |el|'s [=part name list=],
			[=list/append=] |el| to |outerRoot|'s [=part element map=][|name|].
		2. If |el| is a [=shadow host=] itself
			then let |innerRoot| be its shadow root.
		3. [=calculate the part element map|Calculate=] |innerRoot|'s [=part element map=].
		4. For each |innerName|/|outerName| in |el|'s [=forwarded part name list=]:
			1. If |innerName| is an ident:
				1. Let |innerParts| be |innerRoot|'s [=part element map=][|innerName|]
				2. [=list/Append=] the elements in |innerParts|
					to |outerRoot|'s [=part element map=][|outerName|]
			2. If |innerName| is a pseudo-element name:
				1. [=list/Append=] |innerRoot|'s pseudo-element(s) with that name
					to |outerRoot|'s [=part element map=][|outerName|].
</div>

Motivation {#motivation}
------------------------

For custom elements to be fully useful and as capable as built-in elements
it should be possible for parts of them to be styled from outside.
Exactly what can be styled from outside should be controlled by the element author.
Also, it should be possible for a custom element to present a stable "API" for styling.
That is, the selector used to style a part of a custom element
should not expose or require knowledge of the internal details of the element.
The custom element author should be able to change the internal details of the element
while leaving the selectors untouched.

The previous proposed method for styling inside the shadow tree,
the >>> combinator,
turned out to be <em>too powerful</em> for its own good;
it exposed too much of a component's internal structure to scrutiny,
defeating some of the encapsulation benefits that using Shadow DOM brings.
For this,
and other performance-related reasons,
the >>> combinator was eventually dropped.

This left us with using <a>custom properties</a> as the only way to style into a shadow tree:
the component would advertise that it uses certain <a>custom properties</a> to style its internals,
and the outer page could then set those properties as it wished on the <a>shadow host</a>,
letting inheritance push the values down to where they were needed.
This works very well for many simple theming use-cases.

However, there are some cases where this falls down.
If a component wishes to allow arbitrary styling of something in its shadow tree,
the only way to do so is to define hundreds of <a>custom properties</a>
(one per CSS property they wish to allow control of),
which is obviously ridiculous
for both usability and performance reasons.
The situation is compounded if authors wish to style the component differently
based on pseudo-classes like '':hover'';
the component needs to duplicate the <a>custom properties</a> used
for each pseudo-class
(and each combination,
like '':hover:focus'',
resulting in a combinatorial explosion).
This makes the usability and performance problems even worse.

We introduce ''::part()'' to handle this case much more elegantly and performantly.
Rather than bundling everything into <a>custom property</a> names,
the functionality lives in selectors and style rule syntax,
like it's meant to.
This is far more usable for both component authors
and component users,
should have much better performance,
and allows for better encapsulation/API surface.

It's important to note that ''::part()''
offers <em>absolutely zero new theoretical power</em>.
It is not a rehash of the <css>>>></css> combinator,
it is simply a more convenient and consistent syntax
for something authors can already do with <a>custom properties</a>.
By separating out the explicitly "published" parts of an element
(the <a>part element map</a>)
from the sub-parts that it merely happens to contain,
it also helps with encapsulation,
as authors can use ''::part()'' without fear of accidental over-styling.


<!-- Big Text: part=""

████▌   ███▌  ████▌  █████▌      ▐█▌ ▐█▌ ▐█▌ ▐█▌
█▌  █▌ ▐█ ▐█  █▌  █▌   █▌        ▐█▌ ▐█▌ ▐█▌ ▐█▌
█▌  █▌ █▌  █▌ █▌  █▌   █▌   ████  █   █   █   █
████▌  █▌  █▌ ████▌    █▌
█▌     █████▌ █▌▐█     █▌   ████
█▌     █▌  █▌ █▌ ▐█    █▌
█▌     █▌  █▌ █▌  █▌   █▌
-->
Naming a Shadow Element: the <{html-global/part}> attribute {#part-attr}
------------------------------------------------------------------------

Any element in a shadow tree can have a <dfn element-attr for=html-global>part</dfn> attribute.
This is used to expose the element outside of the <a>shadow tree</a>.

<wpt pathprefix="/css/css-shadow-parts/">
	invalidation-change-part-name-forward.html
	invalidation-change-part-name.html
</wpt>

The part attribute is parsed as a space-separated list of tokens representing the part names of this element.

Note: It's okay to give a part multiple names.
The "part name" should be considered similar to a class,
not an id or tagname.

<pre class="example">
&lt;style>
	c-e<b>::part(textspan)</b> { color: red; }
&lt;/style>

&lt;template id="c-e-template">
	&lt;span <b>part="textspan"</b>>This text will be red&lt;/span>
&lt;/template>
&lt;c-e>&lt;/c-e>
&lt;script>
	// Add template as custom element c-e
	...
&lt;/script>
</pre>

<!-- Big Text: exportparts

█████▌ █     █ ████▌   ███▌  ████▌  █████▌ ████▌   ███▌  ████▌  █████▌  ███▌
█▌      █   █  █▌  █▌ █▌  █▌ █▌  █▌   █▌   █▌  █▌ ▐█ ▐█  █▌  █▌   █▌   █▌  █▌
█▌       █ █   █▌  █▌ █▌  █▌ █▌  █▌   █▌   █▌  █▌ █▌  █▌ █▌  █▌   █▌   █▌
████      █    ████▌  █▌  █▌ ████▌    █▌   ████▌  █▌  █▌ ████▌    █▌    ███▌
█▌       █ █   █▌     █▌  █▌ █▌▐█     █▌   █▌     █████▌ █▌▐█     █▌       █▌
█▌      █   █  █▌     █▌  █▌ █▌ ▐█    █▌   █▌     █▌  █▌ █▌ ▐█    █▌   █▌  █▌
█████▌ █     █ █▌      ███▌  █▌  █▌   █▌   █▌     █▌  █▌ █▌  █▌   █▌    ███▌
-->
Forwarding a Shadow Element: the <{html-global/exportparts}> attribute {#exportparts-attr}
------------------------------------------------------------------------------------------

Any element in a shadow tree can have a <dfn element-attr for=html-global>exportparts</dfn> attribute.
If the element is a shadow host,
this is used to allow styling of parts from hosts inside the <a>shadow tree</a>
by rules outside this the <a>shadow tree</a>
(as if they were elements in the same tree as the host,
named by a part attribute).

<wpt pathprefix="/css/css-shadow-parts/">
	both-part-and-exportparts.html
	exportparts-different-scope.html
	exportparts-layered.html
	exportparts-multiple.html
	invalidation-change-exportparts-forward.html
</wpt>

The exportparts attribute is parsed as a comma-separated list of part mappings.
Each part mapping is one of:

<dl class=switch>
	: <code>innerIdent : outerIdent</code>
	:: Adds <code>innerIdent</code>/<code>outerIdent</code> to el's <a>forwarded part name list</a>.

	: <code>ident</code>
	:: Adds <code>ident</code>/<code>ident</code> to el's <a>forwarded part name list</a>.

		Note: This is shorthand for <code>ident : ident</code>.

	: <code>::ident : outerIdent</code>
	:: If <code>::ident</code> is the name of a [=fully styleable pseudo-element=],
		adds <code>::ident</code>/<code>outerIdent</code>
		to el's [=forward part name list=].
		Otherwise, does nothing.

	: anything else
	:: Ignored for error-recovery / future compatibility.
</dl>

Note: It's okay to map a sub-part to several names.

<pre class="example">
&lt;style>
	c-e<b>::part(textspan)</b> { color: red; }
&lt;/style>

&lt;template id="c-e-outer-template">
	&lt;c-e-inner <b>exportparts="innerspan: textspan"</b>>&lt;/c-e-inner>
&lt;/template>

&lt;template id="c-e-inner-template">
	&lt;span <b>part="innerspan"</b>>
		This text will be red because the containing shadow
		host forwards <b>innerspan</b> to the document as "textspan"
		and the document style matches it.
	&lt;/span>
	&lt;span <b>part="textspan"</b>>
		This text will not be red because <b>textspan</b> in the document style
		cannot match against the part inside the inner custom element
		if it is not forwarded.
	&lt;/span>
&lt;/template>

&lt;c-e>&lt;/c-e>
&lt;script>
	// Add template as custom elements c-e-inner, c-e-outer
	...
&lt;/script>
</pre>

<div class=example>
	For example, a [=fully styleable pseudo-element=]
	can be used in the <{html-global/exportparts}> attribute,
	to masquerade as a ''::part()''
	for the component it's in:

	<xmp class=html>
		<template id=custom-element-template>
			<p exportparts="::before : preceding-text, ::after : following-text">
				Main text.
		</template>
	</xmp>

	An element using that template
	can use a selector like ''x-component::part(preceding-text)''
	to target the ''p::before'' pseudo-element in its shadow,
	so users of the component don't need to know
	that the preceding text is implemented as a pseudo-element.
</div>


<!-- Big Text: ::part()

 █▌   █▌  ████▌   ███▌  ████▌  █████▌   ██ ██
███▌ ███▌ █▌  █▌ ▐█ ▐█  █▌  █▌   █▌    █▌   ▐█
 █▌   █▌  █▌  █▌ █▌  █▌ █▌  █▌   █▌   █▌     ▐█
		  ████▌  █▌  █▌ ████▌    █▌   █▌     ▐█
 █▌   █▌  █▌     █████▌ █▌▐█     █▌   █▌     ▐█
███▌ ███▌ █▌     █▌  █▌ █▌ ▐█    █▌    █▌   ▐█
 █▌   █▌  █▌     █▌  █▌ █▌  █▌   █▌     ██ ██
-->

Selecting a Shadow Element: the ''::part()'' pseudo-element {#part}
-------------------------------------------------------------------

The <dfn selector>::part()</dfn> pseudo-element
allows you to select elements that have been exposed via a <{html-global/part}> attribute.
The syntax is:

<pre class=prod>
	::part() = ::part( <<ident>>+ )
</pre>

<wpt pathprefix="/css/css-shadow-parts/">
	host-part-001.html
	host-part-002.html
	host-part-003.html
	host-part-nesting.html
	multiple-scopes.html
</wpt>

The ''::part()'' pseudo-element only matches anything
when the <a>originating element</a> is a <a>shadow host</a>.

<div class="example">
	For example,
	if you have a custom button
	that contains a "label" element that is exposed for styling
	(via <code>part="label"</code>),
	you can select it with
	''x-button::part(label)''.
</div>

<div class="example">
	Part names act similarly to classes:
	multiple elements can have the same part name,
	and a single element can have multiple part names.

	A tabstrip control might have multiple elements
	with <code>part="tab"</code>,
	all of which are selected by ''::part(tab)''.

	If a single tab is active at a time,
	it can be specially indicated with <code>part="tab active"</code>
	and then selected by ''::part(tab active)''
	(or ''::part(active tab)'', as order doesn't matter).
</div>

The ''::part()'' pseudo-element is a [=fully styleable pseudo-element=].
If the <a>originating element's</a> <a>shadow root's</a> <a>part element map</a>
[=map/contains=] the specified <<ident>>,
''::part()'' represents the elements keyed to that ident;
if multiple idents are provided and the [=part element map=] contains them all,
it represents the intersection of the elements keyed to each ident.
Otherwise, it matches nothing.

''::part()'' pseudo-elements inherit according to their position
in the [=originating element's=] shadow tree.

<div class=example>
	For example,
	''x-panel::part(confirm-button)::part(label)''
	never matches anything.
	This is because doing so would expose more structural information
	than is intended.

	If the <code>&lt;x-panel></code>'s internal confirm button had used something like
	<code>part="label => confirm-label"</code>
	to forward the button's internal parts up into the panel's own <a>part element map</a>,
	then a selector like
	''x-panel::part(confirm-label)''
	would select just the one button's label,
	ignoring any other labels.
</div>


<!-- Big Text: CSSOM

 ███▌   ███▌   ███▌   ███▌  █     █
█▌  █▌ █▌  █▌ █▌  █▌ █▌  █▌ ██   ██
█▌     █▌     █▌     █▌  █▌ █▌█ █▐█
█▌      ███▌   ███▌  █▌  █▌ █▌ █ ▐█
█▌         █▌     █▌ █▌  █▌ █▌   ▐█
█▌  █▌ █▌  █▌ █▌  █▌ █▌  █▌ █▌   ▐█
 ███▌   ███▌   ███▌   ███▌  █▌   ▐█
-->

Extensions to the {{Element}} Interface {#idl}
----------------------------------------------

<pre class=idl>
partial interface Element {
	[SameObject, PutForwards=value] readonly attribute DOMTokenList part;
};
</pre>

<wpt pathprefix="/css/css-shadow-parts/">
	idlharness.html
	invalidation-change-part-name-idl-domtokenlist.html
	invalidation-change-part-name-idl-setter.html
	part-name-idl.html
</wpt>

The part attribute’s getter must return a DOMTokenList object
whose associated element is the context object
and whose associated attribute’s local name is part.
The token set of this particular DOMTokenList object are also known as the element’s parts.

Issue(w3c/csswg-drafts#3424): Define this as a superglobal in the DOM spec.

Microsyntaxes for parsing {#parsing}
------------------------------------

<h4 id='parsing-mapping'>
Rules for parsing part mappings</h4>

A <dfn export>valid part mapping</dfn> is a [=tuple=] of tokens
separated by a U+003A COLON character
and any number of space characters before or after the U+003A COLON
The tokens must not contain U+003A COLON or U+002C COMMA characters.

The rules for parsing a part mapping are as follows:

1. Let <var>input</var> be the string being parsed.

1. Let <var>position</var> be a pointer into <var>input</var>, initially pointing at the start of the string.

1. [=Collect a sequence of code points=] that are space characters
1. [=Collect a sequence of code points=] that are not space characters or U+003A COLON characters,
	and let <var>first token</var> be the result.
1. If <var>first token</var> is empty then return error.
1. [=Collect a sequence of code points=] that are space characters.
1. If the end of the <var>input</var> has been reached, return the [=tuple=] (<var>first token</var>, <var>first token</var>)
1. If character at <var>position</var> is not a U+003A COLON character, return error.
1. Consume the U+003A COLON character.
1. [=Collect a sequence of code points=] that are space characters.
1. [=Collect a sequence of code points=] that are not space characters or U+003A COLON characters.
	and let <var>second token</var> be the result.
1. If <var>second token</var> is empty then return error.
1. [=Collect a sequence of code points=] that are space characters.
1. If <var>position</var> is not past the end of <var>input</var> then return error.
1. Return the [=tuple=] (<var>first token</var>, <var>second token</var>).

<h4 id='parsing-mapping-list'>
Rules for parsing a list of part mappings</h4>

A <dfn export>valid list of part mappings</dfn> is a number of valid part mappings
separated by a U+002C COMMA character
and any number of space characters before or after the U+002C COMMA

The rules for parsing a list of part mappings are as follow:

1. Let <var>input</var> be the string being parsed.

1. [=split a string on commas|Split the string <var>input</var> on commas=].
	Let <var>unparsed mappings</var> be the resulting list of strings.

1. Let <var>mappings</var> be an initially empty [=list=] of [=tuples=] of tokens.
	This [=list=] will be the result of this algorithm.

1. For each string <var>unparsed mapping</var> in <var>unparsed mappings</var>,
	run the following substeps:

	1. If <var>unparsed mapping</var> is empty or contains only space characters,
		continue to the next iteration of the loop.
	1. Let <var>mapping</var> be the result of parsing <var>unparsed mapping</var>
		using the <span>rules for parsing part mappings</span>.
	1. If <var>mapping</var> is an error then continue to the next iteration of the loop.
		This allows clients to skip over new syntax that is not understood.
	1. Append <var>mapping</var> to <var>mappings</var>.


Changes {#changes}
==================

	The following significant changes were made since the
	<a href="https://www.w3.org/TR/2014/WD-css-scoping-1-20140403/">3 April 2014 Working Draft</a>.

	* Defined that tree-scoped names inherit into descendant shadow trees
	* Renamed <css>::content</css> to ''::slotted''.
	* Define the flattened tree.
	* Generally reorg and rebase the Shadow DOM section on top of current DOM.
	* Punt <css>@scope</css> and related things,
		and <css>::region</css> and related things,
		to the next level of the draft.
	* Define the specificity of '':host'', '':host()'', '':host-context()'', and ''::slotted()''
	* Remove the <css>>>></css> (previously called <css>/deep/</css>) combinator.
	* Define that tree-abiding pseudos are allowed after ''::slotted()''.
	* Allow <<compound-selector-list>> in all the pseudos.
	* Define a way to create a stylesheet of default element styles for a given element.
	* Make featureless elements match nothing.
	* Define <a>in the context of a shadow tree</a>.
	* Merged [[css-shadow-parts]] and renamed the specification to CSS Shadow Module Level 1. (<a href="https://github.com/w3c/csswg-drafts/issues/5809#issuecomment-910896765">Issue #5809</a>)
	* Added support for multiple names in ''::part()''
	* Renamed 'part name map' to [=forwarded part name list=]
	* Restructured 'part element list' algorithm
	* Moved various ''::part()'' details to [=fully styleable pseudo-element=]
	* Added Web Platform Tests coverage
	* Minor editorial improvements

Privacy Considerations {#privacy}
=================================

This specification introduces Shadow DOM and some shadow-piercing capabilities,
but this does not introduce any privacy issues --
shadow DOM, as currently specified, is intentionally not a privacy boundary
(and the parts of the UA that use shadow DOM and <em>do</em> have a privacy boundary
implicitly rely on protections not yet specified,
which protect them from the things defined in this specification).

Security Considerations {#security}
===================================

This specification introduces Shadow DOM and some shadow-piercing capabilities,
but this does not introduce any security issues --
shadow DOM, as currently specified, is intentionally not a security boundary,
merely a convenience for page authors.
Exposing [=shadow trees=] to selectors in this way introduces no new security considerations.
(And the parts of the UA that use shadow DOM and <em>do</em> have a security boundary
implicitly rely on protections not yet specified,
which protect them from the things defined in this specification).

<wpt hidden>
	chrome-1492368-crash.html
</wpt>
