SlideShare a Scribd company logo
1 of 35
Download to read offline
Get hyper-excited for web standards - Codemotion Rome 2019 1/35
1. Web Components
2. Custom Elements
3. hyperHTML & HyperHTMLElement
Get hyper-excited for web standards - Codemotion Rome 2019 2/35
Foreword
Not trying to convince you to abandon React/Angular/
Vue
!
Get hyper-excited for web standards - Codemotion Rome 2019 3/35
Web Components
Get hyper-excited for web standards - Codemotion Rome 2019 4/35
<video controls src="video.mp4"></video>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="date">
<input type="range">
Get hyper-excited for web standards - Codemotion Rome 2019 5/35
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle">
Dropdown button
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
Get hyper-excited for web standards - Codemotion Rome 2019 6/35
Get hyper-excited for web standards - Codemotion Rome 2019 7/35
<tabs>
<pane title="Hello">Hello</pane>
<pane title="World">World</pane>
</tabs>
Get hyper-excited for web standards - Codemotion Rome 2019 8/35
What if want
— Truly reusable components
— Interoperability
Get hyper-excited for web standards - Codemotion Rome 2019 9/35
Web Components
A suit of web standards to define reusable custom
elements
1. Custom Elements
2. Shadow DOM
Get hyper-excited for web standards - Codemotion Rome 2019 10/35
Custom Elements
Create new HTML tags
<c-clock></c-clock>
Codepen
Get hyper-excited for web standards - Codemotion Rome 2019 11/35
const template = document.createElement('template')
template.innerHTML = `
<div>
<h1>Hello, world!</h1>
<h2>It is <span class="time"></span>.</h2>
</div>
`
class Clock extends HTMLElement {
constructor() {
super();
this.appendChild(template.content.cloneNode(true))
this.timeEl = this.querySelector('.time')
}
connectedCallback() {
this.token = window.setInterval(() => {
this.timeEl.textContent = new Date().toLocaleTimeString();
}, 1000)
}
disconnectedCallback() {
if (this.token) window.clearInterval(this.token);
}
}
customElements.define('c-clock', Clock)
Get hyper-excited for web standards - Codemotion Rome 2019 12/35
Custom Element
Lifecycle
Get hyper-excited for web standards - Codemotion Rome 2019 13/35
Tic-tac-toe XO
in React
Get hyper-excited for web standards - Codemotion Rome 2019 14/35
<c-square value="X"></c-square>
const template = document.createElement('template')
template.innerHTML = `<button class="square"></button>`
class Square extends HTMLElement {
static get observedAttributes() {
return ['value']
}
get value() { return this.getAttribute('value') }
set value(val) { this.setAttribute('value', val) }
constructor() {
super();
this.appendChild(template.content.cloneNode(true))
this.btnEl = this.querySelector('.square')
}
attributeChangedCallback(attr, old, curr) {
if (attr === 'value') this.btnEl.textContent = curr;
}
}
customElements.define('c-square', Square)
Get hyper-excited for web standards - Codemotion Rome 2019 15/35
Enter hyperHTML & HyperHTMLElement
class Square extends HyperHTMLElement {
static get observedAttributes() {
return ['value']
}
render() {
return this.html`
<button class="square">
${this.value}
</button>
`
}
}
Square.define('c-square')
Get hyper-excited for web standards - Codemotion Rome 2019 16/35
HyperHTML
Element
Get hyper-excited for web standards - Codemotion Rome 2019 17/35
hyperHTML (4kB)
const render = hyperHTML.bind(document.body);
function tick() {
render`
<div>
<h1>Hello, world!</h1>
<h2>It is ${new Date().toLocaleTimeString()}.</h2>
</div>
`;
}
setInterval(tick, 1000);
Codepen
Get hyper-excited for web standards - Codemotion Rome 2019 18/35
Tagged template literal
function html(chunks, ...interpolations) {
console.log(chunks); // ['1 ', ' 3']
console.log(interpolations); // [2] or [4]
}
html`1 ${2} 3`;
html`1 ${4} 3`;
Get hyper-excited for web standards - Codemotion Rome 2019 19/35
Efficient DOM
const bodyRender = hyperHTML.bind(document.body);
const names = [
{ name: 'First item' },
{ name: 'Second item' },
{ name: 'Third item' }
]
hyperHTML.bind(document.body)`
<h1>${document.title}</h1>
<ul>
${names.map(item => `<li>${item.name}</li>`)}
</ul>
`;
Get hyper-excited for web standards - Codemotion Rome 2019 20/35
Levenshtein algorithm
domdiff based on petit-dom
Get hyper-excited for web standards - Codemotion Rome 2019 21/35
Not primitive types
customElements.define('h-welcome', class HyperWelcome extends HTMLElement {
constructor() {
super();
this.html = hyperHTML.bind(this);
}
get user() { return this._user; }
set user(value) { this._user = value; this.render(); }
render() { return this.html`<h1>Hello, ${this._user.name}</h1>`; }
}
);
hyperHTML.bind(document.getElementById('root'))`
<h-welcome user=${{ name: 'Sara' }} />
<h-welcome user=${{ name: 'Cahal' }} />
`;
Get hyper-excited for web standards - Codemotion Rome 2019 22/35
HyperHTMLElement
Get hyper-excited for web standards - Codemotion Rome 2019 23/35
class Game extends HyperHTMLElement {
get defaultState() {
return { history: [], stepNumber: 0 };
}
handleClick(event) { this.setState({ ... }); }
render() {
const current = this.state.history[this.state.stepNumber];
return this.html`
<div class="game-board">
<c-board
squares=${current.squares}
onsquareclick=${e => this.handleClick(e.detail)}
/>
</div>
`;
}
}
Get hyper-excited for web standards - Codemotion Rome 2019 24/35
Server side
rendering with
viperHTML
Get hyper-excited for web standards - Codemotion Rome 2019 25/35
hyperHTML vs lit-html vs omi
vs lit-html 1.0
Tencent/omi
Get hyper-excited for web standards - Codemotion Rome 2019 26/35
Custom Elements in React
— custom-elements-everywhere
— Web Components in React
Get hyper-excited for web standards - Codemotion Rome 2019 27/35
Use cases for Custom Elements and hyperHTML
— cross-framework UI components and libraries
— Primer - Github
— Vaadin
— Long-lasting web projects
— Lightweight framework-less compiler-less
development
Get hyper-excited for web standards - Codemotion Rome 2019 28/35
Standards are the best way, if not
the only one, to move the Web
forward.
— Andrea Giammarchi
Get hyper-excited for web standards - Codemotion Rome 2019 29/35
Last notes - Redux
export class Homepage extends ConnectedHyperElement {
connectedCallback() {
super.connectedCallback();
getFeeds().then(feeds => this.dispatch(addFeeds(feeds)));
this.render();
}
stateChanged(state) {
this.feeds = state.feeds;
this.render();
}
render() {
console.log(this.feeds)
}
}
Get hyper-excited for web standards - Codemotion Rome 2019 30/35
Last notes - Hooks
import stardust, {html, useState} from 'neverland';
const Counter = stardust(() => {
const [count, setCount] = useState(0);
return html`
<p>You clicked ${count} times</p>
<button onclick=${() => setCount(count + 1)}>
Click me
</button>
`;
});
Get hyper-excited for web standards - Codemotion Rome 2019 31/35
Last notes -Testing
import { Button } from './Button';
describe('<mr-button>', () => {
it('renders correct className', () => {
const element = new Button();
element.setAttribute('kind', 'primary');
element.render();
const button = element.querySelector('button');
expect(button.classList.contains('button--primary')).toBe(true);
});
});
Get hyper-excited for web standards - Codemotion Rome 2019 32/35
One last slide...
Get hyper-excited for web standards - Codemotion Rome 2019 33/35
Jiayi Hu
[dʒʌɪ]
Front-end developer
— Twitter: @jiayi_ghu
— GitHub: github.com/jiayihu/talks
— italiajs.slack.com
Get hyper-excited for web standards - Codemotion Rome 2019 34/35
Get hyper-excited
Get hyper-excited for web standards - Codemotion Rome 2019 35/35

More Related Content

Similar to Jiayi Hu - Get hyper-excited for web standards - Codemotion Rome 2019

[HEWEBAR 2012] Adaptive Images in Responsive Web Design
[HEWEBAR 2012] Adaptive Images in Responsive Web Design[HEWEBAR 2012] Adaptive Images in Responsive Web Design
[HEWEBAR 2012] Adaptive Images in Responsive Web Design
Christopher Schmitt
 

Similar to Jiayi Hu - Get hyper-excited for web standards - Codemotion Rome 2019 (20)

PyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdfPyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdf
 
Presentation Tier optimizations
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
 
Modern android development
Modern android developmentModern android development
Modern android development
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence Connect
 
[HEWEBAR 2012] Adaptive Images in Responsive Web Design
[HEWEBAR 2012] Adaptive Images in Responsive Web Design[HEWEBAR 2012] Adaptive Images in Responsive Web Design
[HEWEBAR 2012] Adaptive Images in Responsive Web Design
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Java script
Java scriptJava script
Java script
 
Folio3 - An Introduction to PHP Yii
Folio3 - An Introduction to PHP YiiFolio3 - An Introduction to PHP Yii
Folio3 - An Introduction to PHP Yii
 
Angular 2 and Wijmo 5 - GrapeCity Echo 2016 Tokyo
Angular 2 and Wijmo 5 - GrapeCity Echo 2016 TokyoAngular 2 and Wijmo 5 - GrapeCity Echo 2016 Tokyo
Angular 2 and Wijmo 5 - GrapeCity Echo 2016 Tokyo
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017
 
Mvc - Titanium
Mvc - TitaniumMvc - Titanium
Mvc - Titanium
 
Dropwizard Introduction
Dropwizard IntroductionDropwizard Introduction
Dropwizard Introduction
 
ql.io at NodePDX
ql.io at NodePDXql.io at NodePDX
ql.io at NodePDX
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in Angular
 
Computer science class 12 project on Super Market Billing
Computer science class 12 project on Super Market BillingComputer science class 12 project on Super Market Billing
Computer science class 12 project on Super Market Billing
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 

More from Codemotion

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Jiayi Hu - Get hyper-excited for web standards - Codemotion Rome 2019

  • 1. Get hyper-excited for web standards - Codemotion Rome 2019 1/35
  • 2. 1. Web Components 2. Custom Elements 3. hyperHTML & HyperHTMLElement Get hyper-excited for web standards - Codemotion Rome 2019 2/35
  • 3. Foreword Not trying to convince you to abandon React/Angular/ Vue ! Get hyper-excited for web standards - Codemotion Rome 2019 3/35
  • 4. Web Components Get hyper-excited for web standards - Codemotion Rome 2019 4/35
  • 5. <video controls src="video.mp4"></video> <select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <input type="date"> <input type="range"> Get hyper-excited for web standards - Codemotion Rome 2019 5/35
  • 6. <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle"> Dropdown button </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </div> Get hyper-excited for web standards - Codemotion Rome 2019 6/35
  • 7. Get hyper-excited for web standards - Codemotion Rome 2019 7/35
  • 8. <tabs> <pane title="Hello">Hello</pane> <pane title="World">World</pane> </tabs> Get hyper-excited for web standards - Codemotion Rome 2019 8/35
  • 9. What if want — Truly reusable components — Interoperability Get hyper-excited for web standards - Codemotion Rome 2019 9/35
  • 10. Web Components A suit of web standards to define reusable custom elements 1. Custom Elements 2. Shadow DOM Get hyper-excited for web standards - Codemotion Rome 2019 10/35
  • 11. Custom Elements Create new HTML tags <c-clock></c-clock> Codepen Get hyper-excited for web standards - Codemotion Rome 2019 11/35
  • 12. const template = document.createElement('template') template.innerHTML = ` <div> <h1>Hello, world!</h1> <h2>It is <span class="time"></span>.</h2> </div> ` class Clock extends HTMLElement { constructor() { super(); this.appendChild(template.content.cloneNode(true)) this.timeEl = this.querySelector('.time') } connectedCallback() { this.token = window.setInterval(() => { this.timeEl.textContent = new Date().toLocaleTimeString(); }, 1000) } disconnectedCallback() { if (this.token) window.clearInterval(this.token); } } customElements.define('c-clock', Clock) Get hyper-excited for web standards - Codemotion Rome 2019 12/35
  • 13. Custom Element Lifecycle Get hyper-excited for web standards - Codemotion Rome 2019 13/35
  • 14. Tic-tac-toe XO in React Get hyper-excited for web standards - Codemotion Rome 2019 14/35
  • 15. <c-square value="X"></c-square> const template = document.createElement('template') template.innerHTML = `<button class="square"></button>` class Square extends HTMLElement { static get observedAttributes() { return ['value'] } get value() { return this.getAttribute('value') } set value(val) { this.setAttribute('value', val) } constructor() { super(); this.appendChild(template.content.cloneNode(true)) this.btnEl = this.querySelector('.square') } attributeChangedCallback(attr, old, curr) { if (attr === 'value') this.btnEl.textContent = curr; } } customElements.define('c-square', Square) Get hyper-excited for web standards - Codemotion Rome 2019 15/35
  • 16. Enter hyperHTML & HyperHTMLElement class Square extends HyperHTMLElement { static get observedAttributes() { return ['value'] } render() { return this.html` <button class="square"> ${this.value} </button> ` } } Square.define('c-square') Get hyper-excited for web standards - Codemotion Rome 2019 16/35
  • 17. HyperHTML Element Get hyper-excited for web standards - Codemotion Rome 2019 17/35
  • 18. hyperHTML (4kB) const render = hyperHTML.bind(document.body); function tick() { render` <div> <h1>Hello, world!</h1> <h2>It is ${new Date().toLocaleTimeString()}.</h2> </div> `; } setInterval(tick, 1000); Codepen Get hyper-excited for web standards - Codemotion Rome 2019 18/35
  • 19. Tagged template literal function html(chunks, ...interpolations) { console.log(chunks); // ['1 ', ' 3'] console.log(interpolations); // [2] or [4] } html`1 ${2} 3`; html`1 ${4} 3`; Get hyper-excited for web standards - Codemotion Rome 2019 19/35
  • 20. Efficient DOM const bodyRender = hyperHTML.bind(document.body); const names = [ { name: 'First item' }, { name: 'Second item' }, { name: 'Third item' } ] hyperHTML.bind(document.body)` <h1>${document.title}</h1> <ul> ${names.map(item => `<li>${item.name}</li>`)} </ul> `; Get hyper-excited for web standards - Codemotion Rome 2019 20/35
  • 21. Levenshtein algorithm domdiff based on petit-dom Get hyper-excited for web standards - Codemotion Rome 2019 21/35
  • 22. Not primitive types customElements.define('h-welcome', class HyperWelcome extends HTMLElement { constructor() { super(); this.html = hyperHTML.bind(this); } get user() { return this._user; } set user(value) { this._user = value; this.render(); } render() { return this.html`<h1>Hello, ${this._user.name}</h1>`; } } ); hyperHTML.bind(document.getElementById('root'))` <h-welcome user=${{ name: 'Sara' }} /> <h-welcome user=${{ name: 'Cahal' }} /> `; Get hyper-excited for web standards - Codemotion Rome 2019 22/35
  • 23. HyperHTMLElement Get hyper-excited for web standards - Codemotion Rome 2019 23/35
  • 24. class Game extends HyperHTMLElement { get defaultState() { return { history: [], stepNumber: 0 }; } handleClick(event) { this.setState({ ... }); } render() { const current = this.state.history[this.state.stepNumber]; return this.html` <div class="game-board"> <c-board squares=${current.squares} onsquareclick=${e => this.handleClick(e.detail)} /> </div> `; } } Get hyper-excited for web standards - Codemotion Rome 2019 24/35
  • 25. Server side rendering with viperHTML Get hyper-excited for web standards - Codemotion Rome 2019 25/35
  • 26. hyperHTML vs lit-html vs omi vs lit-html 1.0 Tencent/omi Get hyper-excited for web standards - Codemotion Rome 2019 26/35
  • 27. Custom Elements in React — custom-elements-everywhere — Web Components in React Get hyper-excited for web standards - Codemotion Rome 2019 27/35
  • 28. Use cases for Custom Elements and hyperHTML — cross-framework UI components and libraries — Primer - Github — Vaadin — Long-lasting web projects — Lightweight framework-less compiler-less development Get hyper-excited for web standards - Codemotion Rome 2019 28/35
  • 29. Standards are the best way, if not the only one, to move the Web forward. — Andrea Giammarchi Get hyper-excited for web standards - Codemotion Rome 2019 29/35
  • 30. Last notes - Redux export class Homepage extends ConnectedHyperElement { connectedCallback() { super.connectedCallback(); getFeeds().then(feeds => this.dispatch(addFeeds(feeds))); this.render(); } stateChanged(state) { this.feeds = state.feeds; this.render(); } render() { console.log(this.feeds) } } Get hyper-excited for web standards - Codemotion Rome 2019 30/35
  • 31. Last notes - Hooks import stardust, {html, useState} from 'neverland'; const Counter = stardust(() => { const [count, setCount] = useState(0); return html` <p>You clicked ${count} times</p> <button onclick=${() => setCount(count + 1)}> Click me </button> `; }); Get hyper-excited for web standards - Codemotion Rome 2019 31/35
  • 32. Last notes -Testing import { Button } from './Button'; describe('<mr-button>', () => { it('renders correct className', () => { const element = new Button(); element.setAttribute('kind', 'primary'); element.render(); const button = element.querySelector('button'); expect(button.classList.contains('button--primary')).toBe(true); }); }); Get hyper-excited for web standards - Codemotion Rome 2019 32/35
  • 33. One last slide... Get hyper-excited for web standards - Codemotion Rome 2019 33/35
  • 34. Jiayi Hu [dʒʌɪ] Front-end developer — Twitter: @jiayi_ghu — GitHub: github.com/jiayihu/talks — italiajs.slack.com Get hyper-excited for web standards - Codemotion Rome 2019 34/35
  • 35. Get hyper-excited Get hyper-excited for web standards - Codemotion Rome 2019 35/35