Shadow DOM, CSS and Styling Hooks in LWC what you need to know

SudiptaDeb 2,188 views 29 slides Feb 12, 2021
Slide 1
Slide 1 of 29
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29

About This Presentation

Shadow DOM, CSS and Styling Hooks in LWC what you need to know


Slide Content

Shadow DOM, CSS
and styling hooks in
LWC: what you need
to know
Alba Rivas, Lead Developer Advocate, Salesforce
11 February 2021

Alba Rivas
Lead Developer Advocate
[email protected], @AlbaSFDC

Forward-Looking Statement
Salesforce Confidential. Not for external distribution.
Presentation Name | Slide #
Statement under the Private Securities Litigation Reform Act of 1995:
This presentation contains forward-looking statements about the company’s financial and operating results, which may include expected GAAP and non-GAAP financial and other
operating and non-operating results, including revenue, net income, diluted earnings per share, operating cash flow growth, operating margin improvement, expected revenue
growth, expected current remaining performance obligation growth, expected tax rates, the one-time accounting non-cash charge that was incurred in connection with the
Salesforce.org combination; stock-based compensation expenses, amortization of purchased intangibles, shares outstanding, market growth and sustainability goals. The
achievement or success of the matters covered by such forward-looking statements involves risks, uncertainties and assumptions. If any such risks or uncertainties materialize or if any
of the assumptions prove incorrect, the company’s results could differ materially from the results expressed or implied by the forward-looking statements we make.
The risks and uncertainties referred to above include -- but are not limited to -- risks associated with the effect of general economic and market conditions; the impact of geopolitical
events; the impact of foreign currency exchange rate and interest rate fluctuations on our results; our business strategy and our plan to build our business, including our strategy to be
the leading provider of enterprise cloud computing applications and platforms; the pace of change and innovation in enterprise cloud computing services; the seasonal nature of our
sales cycles; the competitive nature of the market in which we participate; our international expansion strategy; the demands on our personnel and infrastructure resulting from
significant growth in our customer base and operations, including as a result of acquisitions; our service performance and security, including the resources and costs required to avoid
unanticipated downtime and prevent, detect and remediate potential security breaches; the expenses associated with new data centers and third-party infrastructure providers;
additional data center capacity; real estate and office facilities space; our operating results and cash flows; new services and product features, including any efforts to expand our
services beyond the CRM market; our strategy of acquiring or making investments in complementary businesses, joint ventures, services, technologies and intellectual property rights;
the performance and fair value of our investments in complementary businesses through our strategic investment portfolio; our ability to realize the benefits from strategic
partnerships, joint ventures and investments; the impact of future gains or losses from our strategic investment portfolio, including gains or losses from overall market conditions that
may affect the publicly traded companies within the company's strategic investment portfolio; our ability to execute our business plans; our ability to successfully integrate acquired
businesses and technologies, including delays related to the integration of Tableau due to regulatory review by the United Kingdom Competition and Markets Authority; our ability to
continue to grow unearned revenue and remaining performance obligation; our ability to protect our intellectual property rights; our ability to develop our brands; our reliance on
third-party hardware, software and platform providers; our dependency on the development and maintenance of the infrastructure of the Internet; the effect of evolving domestic
and foreign government regulations, including those related to the provision of services on the Internet, those related to accessing the Internet, and those addressing data privacy,
cross-border data transfers and import and export controls; the valuation of our deferred tax assets and the release of related valuation allowances; the potential availability of
additional tax assets in the future; the impact of new accounting pronouncements and tax laws; uncertainties affecting our ability to estimate our tax rate; the impact of expensing
stock options and other equity awards; the sufficiency of our capital resources; factors related to our outstanding debt, revolving credit facility, term loan and loan associated with 50
Fremont; compliance with our debt covenants and lease obligations; current and potential litigation involving us; and the impact of climate change.
Further information on these and other factors that could affect the company’s financial results is included in the reports on Forms 10-K, 10-Q and 8-K and in other filings it makes
with the Securities and Exchange Commission from time to time. These documents are available on the SEC Filings section of the Investor Information section of the company’s
website at www.salesforce.com/investor.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements, except as required by law.

Agenda
●Shadow DOM
●LWC Shadow DOM implementations
●CSS & LWC
●CSS Custom Properties
●Styling Hooks
●Ways to import and share CSS
●SLDS Validator

Lightning Web Components

Native Shadow DOM

Shadow DOM
#shadow-root
|_h1
|_span

html
|_head
|_title
|_style
|_body
|_h1
|_div
|_span
|_p
|_a

html
|_head
|_title
|_style
|_body
|_h1
|_div →
|_span
|_p
|_a

shadow
boundary
shadow
host
const el = document.querySelector( 'div');
const shadowRoot = el.attachShadow({mode: 'open'});
shadowRoot.innerHTML = "<h1>I belong to <span>Shadow DOM</span></h1>" ;
html
|_head
|_title
|_style
|_body
|_h1
|_div
|_h1
|_span
|_span
|_p
|_a

Flattened DOM
Light DOM
Shadow DOM

Native Shadow DOM

Shadow DOM
Encapsulates:

●Markup: shadow DOM elements are queried differently,
and only possible if the shadow tree is ‘open’

●Behaviour: events need to be configured as composed
and bubbles to escape the shadow boundary
○All UA-dispatched UI events are composed
(click/touch/mouseover/copy/paste , etc.).

●CSS: CSS cascading doesn’t affect inner shadow DOM
elements - inherited CSS properties do. More later!
el.shadowRoot.querySelector('h1')

const selectEvent = new
CustomEvent('contactselect', {
bubbles: true,
composed: true
});

Not available if closed mode

Shadow DOM in Vanilla Web
Components
class cascadingAndInheritance extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
console.log(this.shadowRoot.querySelector('h1'))
}
}

Elements of vanilla Web Components are enclosed in a native Shadow DOM Tree
Native Shadow DOM (Vanilla Web Components)

Shadow DOM in LWC
Elements of LWCs are enclosed in a Native or Synthetic Shadow DOM Tree


class MyLightningWebComponent extends LightningElement {
connectedCallback() {
console.log(this.template.querySelector('h1'))
}
}

LWC OSS (Synthetic)
Shadow DOM in LWC
LWC on platform (Synthetic) - backwards compatibility
LWC OSS (Native) - default

Cascading vs Inheritance

CSS
Cascading → combining CSS rules in different stylesheets that are applied to an
element
Inheritance → some CSS property values set on parent elements are inherited by their
child elements, if no cascaded value found - only some (color, font-...)
Property value =
Property initial value
Cascaded
value?
Inherited
property?
Property value =
Property value on
parent element
Property value =
Cascaded value
YES
NO
YES
NO

Cascading vs Inheritance

CSS
h1 {
color: red;
}

h1 {
color: blue;
}
div {
color: green;
}
span {
color: orange;
}
<h1>Salesforce Mascots Stories</ h1>
<div>
<p>Astro and Codey are < span>good friends!</span></p>
</div>
Cascaded value
Inherited value
Cascaded Value

Prevent inheritance from affecting your styles
Either explicitly set the color, or revert them to their original state

CSS & LWC OSS - Native
<template>
<h1>I belong to parent component Shadow DOM</ h1>
<div><my-cascading-and-inheritance ></my-cascading-and-inheritance ></div>
</template>
h1 {
color: red;
}

h1 {
color: blue;
}
div {
color: green;
}
span {
color: orange;
}
<template>
<h1>I belong to child component Shadow DOM</ h1>
<p>Astro and Codey are < span>good friends!</span></p>
</template>

cascadingAndInheritance.html
cascadingAndInheritanceContainer.html
cascadingAndInheritanceContainer.css
shadow boundary

CSS & LWC / LWC OSS - Synthetic
<template>
<h1>I belong to parent component Shadow DOM</ h1>
<div><c-cascading-and-inheritance ></c-cascading-and-inheritance ></div>
</template>
h1 {
color: red;
}

h1 {
color: blue;
}
div {
color: green;
}
span {
color: orange;
}
<template>
<h1>I belong to child component Shadow DOM</ h1>
<p>Astro and Codey are < span>good friends!</span></p>
</template>

cascadingAndInheritance.html
cascadingAndInheritanceContainer.html cascadingAndInheritanceContainer.css
SLDS Styles or
styles loaded
via loadStyle
not scoped!!

CSS Custom Properties
(CSS Variables)
Entities to allow reusing CSS property values
●Defined on a scope, and accessed with var
●Case sensitive
●Can penetrate Shadow DOM
Used in LWC for
●Styling Hooks
●Aura Design Tokens
●SLDS Design Tokens
Need to be allowed explicitly in LWC OSS
Set a Custom Property
Get a Custom Property

Setting CSS Custom Properties from JS

Styling Hooks (beta)
CSS Custom Properties defined in base components and SLDS blueprints to allow
customization




Looking for feedback → sfdc.co/stylinghooks
Global Styling Hooks coming soon!

Styling Hooks (beta)
Best practice: Don’t override standard styles. Use Styling hooks.

Aura Design Tokens
Use CSS Variables to access Aura design tokens both in Aura and LWC
Reuse CSS across Aura and LWC!


.THIS h1 {
color : token(myTitleColor);
}

h1 {
color: var(--c-myTitleColor);
}
<aura:tokens>
<aura:token name="myTitleColor" value="blue"/>
</aura:tokens>
Aura LWC

SLDS Design Tokens
lightningdesignsystem.com/design-tokens

Importing CSS
Single File Multiple Files
Static Resource
Styles scoped globally (same as SLDS) - when using synthetic shadow

Importing CSS
Create a LWC with just the CSS file


Import using the syntax @import <namespace>/<componentname>


Styles scoped to the component
Best practice: create a shared CSS Module with all your CSS Custom Properties
CSS modules
importCSSsharedModule.css

Cascading Order
If different rules for the same selector, the following will have preference, in order:
●Inline styles
●CSS defined in component CSS file (scoped)
●CSS imported using @import (scoped)
●CSS imported with loadStyle (global) - only apply if synthetic

Sharing Tokens and Properties
Create Aura Design Tokens to reuse config across Aura and LWC
Create a Shared CSS Module with all CSS Custom Properties
Global Styling Hooks coming soon!

SLDS Validator
VSCode plugin
Part of Salesforce Extension pack

Smart Suggestions
Recommended tokens and utility
classes, in CSS and HTML

Save Time
Syntax highlighting and code
completion

Summary
●Understand Shadow DOM and the different implementations in LWC
●Master CSS: cascading, inherited and custom properties
●Styling hooks, Aura design tokens and SLDS design token
●Know and choose the best ways to import and share your CSS
●SLDS Validator is your friend!

github.com/albarivas/shadow-dom
github.com/albarivas/shadow-dom-oss

Thank You!