KEMBAR78
Magic of web components | PPTX
Magic of
Web Components
By Dmitriy Kalnauz
Magic of Web Components
Play
hys-enterprise.com
HYS Enterprise is a Dutch software
development company with more than
200 talented engineers from all over
the world hys-enterprise.com
Ukraine
Netherlands
How I am
● Software Engineer, sometime Full-stack, sometimes .NET,
sometimes frontend @ HYS Enterprise
● 5+ years of experience
● .NET, JS, Angular, React, Vue, Java, Python, AWS
Magic of Web Components
What are we going
to speak about
What are Web Components
Which problems solves
How to use
Magic of Web Components
Magic of Web Components
Style Guide
is a Problem
Magic of Web Components
Service C
Service B
Service A
Magic of Web Components
User Interface
Business Layer
Data Layer
User Interface
Microservice Microservice
Microservice
MONOLITHIC ARCHITECTURE MICROSERVICES ARCHITECTURE
Magic of Web Components
Event Name
User Interface
Microservice Microservice
Microservice
User Interface User Interface
Magic of Web Components
Challenges deep-dive
Challenge 1
Unified and consistent
UI
● Common/shared UI
library
● CSS variables
Challenge 2
Nobody slapping CSS
of another team
● Scope restriction via
selectors
Challenge 3
Framework Agnostic
Magic of Web Components
Event Name
Menu
component
Header
component
Application
component
Magic of Web Components
Button component
Search component
Calendar component
Schedule component
Notification component
Magic of Web Components
Magic of Web Components
Button component
Dropdown component
Search component
Image component
It's Over 9000!
Potential
Solutions
Solution
Web Components
Custom elements Shadow DOM HTML Templates
Magic of Web Components
Custom Elements
class CustomElement extends HTMLElement {
constructor() {
super();
// ..
}
// ..
}
customElements.define('custom-element', CustomElement);
This API allows developers to define their tags (custom element), whose styles are
encapsulated and isolated (shadow dom), that can be restamped many times (template), and
have a consistent way of being integrated into applications (es module).
Lifecycle Callbacks
class CustomElement extends HTMLElement {
constructor() {
super();
}
connectedCallback() {}
disconnectedCallback() {}
adoptedCallback() {}
attributeChangedCallback(attrName, oldVal, newVal) {}
}
customElements.define('custom-element', CustomElement);
Customized built-in elements
A customized built-in element, which is defined with an extends option. These types of
custom elements have a local name equal to the value passed in their extends option,
and their defined name is used as the value of the is an attribute, which therefore must
be a valid custom element name.
class PlasticButton extends HTMLButtonElement {
// ..
}
customElements.define("plastic-button", PlasticButton, {extends: "button"});
How to use
<custom-element>Click Me!</custom-element>
document.createElement('custom-element');
<button is="custom-button">Click Me!</button>
document.createElement('button', {is:'custom-button'});
● Autonomous custom element via defined tag
● Customized built-in element use the is attribute on a extended element
Shadow DOM
Shadow DOM introduces scoped styles to the web platform. Without tools or naming
conventions, you can bundle CSS with markup, hide implementation details, and author self-
contained components in vanilla JavaScript.
class CustomElement extends HTMLElement {
constructor() {
super();
var div = document.createElement("div");
div.innerHTML = "Hello world";
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(div);
}
}
customElements.define("custom-element", CustomElement);
HTML Template
<template>
<div class="modal">
<style>
:host(my-modal) {display: none;}
.modal{background-color: #fefefe;border: 1px solid #888;}
</style>
<div class="modal-header">
<div class="modal-header__title">
<slot name="header"></slot>
</div>
<div class="icon icon-close" style="position: relative;">&times;</div>
</div>
<div class="modal-content">
<slot name="content"></slot>
</div>
</div>
</template>
The template element is used to declare fragments of HTML that can be cloned and inserted
in the document by script.
Web Components
Magic of Web Components
➮ Custom Elements
➮ Shadow DOM
➮ HTML Templates
➮ HTML Imports
Chrome
(67+)
Opera
(64+)
Firefox
(63+)
Safari
(Limited 10.1+)
Edge
(Chromium(79+))
Stable Stable Stable Stable Stable
Stable Stable Stable Stable Stable
Stable Stable Stable Stable Stable
HTML Imports are deprecated and removed
Lets try
const componentStyle = require('./component.css');
const toastTemplate = document.createElement('template');
toastTemplate.innerHTML = `
<style>${typeof componentStyle === 'object' ? componentStyle.default : componentStyle}</style>
<slot name="content"></slot>
<div class="icon icon-close">&times;</div>
`;
export class AlarmComponent extends HTMLElement {
_type: string;
_element: HTMLElement;
_shadow: any;
get type() {
return this._type;
}
get template() {
return toastTemplate.innerHTML;
}
static get observedAttributes() { return ['type'] }
constructor() {
super();
this._shadow = this.attachShadow({
mode: 'open'
});
this._element = document.createElement('component-content');
this._element.innerHTML = this.template;
this._shadow.appendChild(this._element);
}
connectedCallback() {
this._element.className = this._type || 'default';
var element = this.shadowRoot.querySelector('.icon.icon-close')
.addEventListener('click', e => {this.removeComponent();});
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'type') {
this._element.className = newValue;
this._type = newValue;
}
}
removeComponent = () => this.remove();
}
if (!window.customElements.get('alarm-component')) {
customElements.define('alarm-component', AlarmComponent);
}
alarm-component-content{
color: deepskyblue;
font-size: 18px;
}
alarm-component-content::first-letter{
color:fuchsia;
font-size: 32px;
}
Demo
Magic of Web Components
Pros and cons
Pros
Portable
Dependencies not required
Style isolated
Long term prospect
Execution speed
Cons
Don't have enough community
support
Not widespread
Low level(DX worse)
Check it out
Magic of Web Components
Material
Polymer elements
UI5 Web Components
PatternFly Elements
Sources & Useful links
Magic of Web Components
GitHub with examples: https://github.com/dkalnauz/web-components
Web Components Google documentation: https://developers.google.com/web/fundamentals/web-components
Web Components site: https://www.webcomponents.org/specs
Contacts: facebook.com
linkedin.com/in /dmitriykalnauz
Thank you
For your attention!
Any Questions?
Magic of Web Components

Magic of web components

  • 1.
    Magic of Web Components ByDmitriy Kalnauz Magic of Web Components Play hys-enterprise.com
  • 2.
    HYS Enterprise isa Dutch software development company with more than 200 talented engineers from all over the world hys-enterprise.com Ukraine Netherlands
  • 3.
    How I am ●Software Engineer, sometime Full-stack, sometimes .NET, sometimes frontend @ HYS Enterprise ● 5+ years of experience ● .NET, JS, Angular, React, Vue, Java, Python, AWS Magic of Web Components
  • 4.
    What are wegoing to speak about What are Web Components Which problems solves How to use Magic of Web Components
  • 5.
    Magic of WebComponents Style Guide is a Problem
  • 6.
    Magic of WebComponents Service C Service B Service A
  • 8.
    Magic of WebComponents
  • 9.
    User Interface Business Layer DataLayer User Interface Microservice Microservice Microservice MONOLITHIC ARCHITECTURE MICROSERVICES ARCHITECTURE
  • 10.
    Magic of WebComponents
  • 11.
    Event Name User Interface MicroserviceMicroservice Microservice User Interface User Interface
  • 12.
    Magic of WebComponents
  • 13.
    Challenges deep-dive Challenge 1 Unifiedand consistent UI ● Common/shared UI library ● CSS variables Challenge 2 Nobody slapping CSS of another team ● Scope restriction via selectors Challenge 3 Framework Agnostic Magic of Web Components
  • 14.
  • 15.
    Magic of WebComponents
  • 16.
    Button component Search component Calendarcomponent Schedule component Notification component Magic of Web Components
  • 17.
    Magic of WebComponents Button component Dropdown component Search component Image component It's Over 9000!
  • 18.
  • 19.
  • 20.
    Custom elements ShadowDOM HTML Templates Magic of Web Components
  • 21.
    Custom Elements class CustomElementextends HTMLElement { constructor() { super(); // .. } // .. } customElements.define('custom-element', CustomElement); This API allows developers to define their tags (custom element), whose styles are encapsulated and isolated (shadow dom), that can be restamped many times (template), and have a consistent way of being integrated into applications (es module).
  • 22.
    Lifecycle Callbacks class CustomElementextends HTMLElement { constructor() { super(); } connectedCallback() {} disconnectedCallback() {} adoptedCallback() {} attributeChangedCallback(attrName, oldVal, newVal) {} } customElements.define('custom-element', CustomElement);
  • 23.
    Customized built-in elements Acustomized built-in element, which is defined with an extends option. These types of custom elements have a local name equal to the value passed in their extends option, and their defined name is used as the value of the is an attribute, which therefore must be a valid custom element name. class PlasticButton extends HTMLButtonElement { // .. } customElements.define("plastic-button", PlasticButton, {extends: "button"});
  • 24.
    How to use <custom-element>ClickMe!</custom-element> document.createElement('custom-element'); <button is="custom-button">Click Me!</button> document.createElement('button', {is:'custom-button'}); ● Autonomous custom element via defined tag ● Customized built-in element use the is attribute on a extended element
  • 25.
    Shadow DOM Shadow DOMintroduces scoped styles to the web platform. Without tools or naming conventions, you can bundle CSS with markup, hide implementation details, and author self- contained components in vanilla JavaScript. class CustomElement extends HTMLElement { constructor() { super(); var div = document.createElement("div"); div.innerHTML = "Hello world"; const shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.appendChild(div); } } customElements.define("custom-element", CustomElement);
  • 26.
    HTML Template <template> <div class="modal"> <style> :host(my-modal){display: none;} .modal{background-color: #fefefe;border: 1px solid #888;} </style> <div class="modal-header"> <div class="modal-header__title"> <slot name="header"></slot> </div> <div class="icon icon-close" style="position: relative;">&times;</div> </div> <div class="modal-content"> <slot name="content"></slot> </div> </div> </template> The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.
  • 27.
    Web Components Magic ofWeb Components ➮ Custom Elements ➮ Shadow DOM ➮ HTML Templates ➮ HTML Imports Chrome (67+) Opera (64+) Firefox (63+) Safari (Limited 10.1+) Edge (Chromium(79+)) Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable Stable HTML Imports are deprecated and removed
  • 28.
  • 29.
    const componentStyle =require('./component.css'); const toastTemplate = document.createElement('template'); toastTemplate.innerHTML = ` <style>${typeof componentStyle === 'object' ? componentStyle.default : componentStyle}</style> <slot name="content"></slot> <div class="icon icon-close">&times;</div> `; export class AlarmComponent extends HTMLElement { _type: string; _element: HTMLElement; _shadow: any; get type() { return this._type; } get template() { return toastTemplate.innerHTML; } static get observedAttributes() { return ['type'] }
  • 30.
    constructor() { super(); this._shadow =this.attachShadow({ mode: 'open' }); this._element = document.createElement('component-content'); this._element.innerHTML = this.template; this._shadow.appendChild(this._element); } connectedCallback() { this._element.className = this._type || 'default'; var element = this.shadowRoot.querySelector('.icon.icon-close') .addEventListener('click', e => {this.removeComponent();}); } attributeChangedCallback(name, oldValue, newValue) { if (name === 'type') { this._element.className = newValue; this._type = newValue; } }
  • 31.
    removeComponent = ()=> this.remove(); } if (!window.customElements.get('alarm-component')) { customElements.define('alarm-component', AlarmComponent); }
  • 33.
  • 34.
  • 35.
    Pros and cons Pros Portable Dependenciesnot required Style isolated Long term prospect Execution speed Cons Don't have enough community support Not widespread Low level(DX worse)
  • 36.
    Check it out Magicof Web Components Material Polymer elements UI5 Web Components PatternFly Elements
  • 37.
    Sources & Usefullinks Magic of Web Components GitHub with examples: https://github.com/dkalnauz/web-components Web Components Google documentation: https://developers.google.com/web/fundamentals/web-components Web Components site: https://www.webcomponents.org/specs Contacts: facebook.com linkedin.com/in /dmitriykalnauz
  • 38.
    Thank you For yourattention! Any Questions? Magic of Web Components

Editor's Notes

  • #7 У нас есть Несколько продуктов. И в целом они имеют совершенно разный дизайн. При этом они все сделаны плюс минус одними же программистами, дизайнерами и тд и тп. Технологии могут быть абсолютно разными, их выбор отдан на откуп программистов.
  • #23 Мы как разработчики знает что переиспользование кода это - best practice. Это никогда не было просто для разметки - сложный HTML который иногда нужно писать для интерфейса и то как это иногда можно переиспользовать может быть сущим адом. Веб компоненты предназначены для решения таких проблем - они состоят из трех основных технологий, которые можно вместе использовать для создания универсальных элементов с инкапсулированной функциональностью, и можно повторно использовать без опасения коллизии кода.
  • #25 Для того чтобы определить новый элемент HTML, нам необходимо воспользоваться возможностями JavaScript! Свойство customElements глобального объекта window используется для определения нового пользовательского элемента и обучения браузера тому, как его отображать. Вызовите customElements.define(), передав в качестве параметров имя тега, который хотите создать, и класс (* производный) JavaScript, который наследует свою обобщенную структуру и поведение от базового класса HTMLElement. Функциональные возможности пользовательского элемента определяются при помощи class ES2015 (* спецификация ES6), который наследует свою обобщенную структуру и поведение от HTMLElement. За счет наследования от HTMLElement гарантируется, что пользовательский элемент перенимает весь API DOM (* Document Object Model – объектная модель документа), и обеспечивается то, что любые добавленные к классу свойства/методы становятся частью интерфейса DOM элемента. В имени пользовательского элемента должен содержать дефис (-) . Таким образом, <x-tags> , <my-element> и <my-awesome-app> - допустимые имена, а <tabs> и <foo_bar> - нет. Благодаря этому парсер (* синтаксический анализатор) HTML может отличить пользовательские элементы от стандартных. (При работе с другими приложениями). Вы не можете зарегистрировать один и тот же тэг более одного раза. При попытке это выполнить будет выкунута ошибка DOMException. Как только вы сообщили браузеру о новом тэге, то все. Назад дороги нет. Пользовательские элементы не могут быть самозакрывающимися, поскольку согласно стандарту HTML только несколько элементов могут быть самозакрывающимися. Всегда добавляйте закрывающийся тэг ( drawer ).
  • #26 constructor При создании или обновлении образца элемента. Полезен для инициализации характеристик состояния, регистрации обработчиков событий или создания Shadow DOM . Обратитесь к спецификации для ознакомления с тем, что вы можете выполнить в constructor . connectedCallback каждый раз при добавлении элемента в DOM. Полезен для выполнения кода для настройки элемента, например для получения ресурсов или отображения. Как правило, вам следует стараться отложить выполнение остального кода до наступления этого момента. disconnectedCallback каждый раз при удалении элемента из DOM. Полезен для выполнения кода для завершения работы с элементом. attributeChangedCallback(attrName, oldVal, newVal) при добавлении, удалении, обновлении или замене отслеживаемого атрибута. Также вызывается для задания первоначальных значений при создании элемента парсером или его обновлении. Обратите внимание: обработчик будет вызван только для атрибутов, перечисленных в свойстве observedAttributes. adoptedCallback() при перемещении пользовательского элемента в новый документ (например при вызове document.adoptNode(el) ).
  • #27 Расширение возможностей собственных элементов HTML
  • #29 Теневой DOM («Shadow DOM») используется для инкапсуляции. Благодаря ему в компоненте есть собственное «теневое» DOM-дерево, к которому нельзя просто так обратиться из главного документа, у него могут быть изолированные CSS-правила и т.д.
  • #30 <template> предназначен для хранения шаблона HTML. Браузер полностью игнорирует его содержимое, проверяя лишь синтаксис, но мы можем использовать этот элемент в JavaScript, чтобы создать другие элементы. это механизм для отложенного создания клиентского контента Template можно представить себе как фрагмент контента, сохранённый для последующего использования в документе. Хотя парсер и обрабатывает содержимое элемента <template> во время загрузки страницы, он делает это только чтобы убедиться в валидности содержимого; само содержимое при этом не отображается <slot> является частью набора технологии Web Components, является заполнителем внутри веб компонента, которые заполнить собственной разметкой, которая позволяет создавать отдельные деревья DOM и представлять их вместе. Слоты идентифицируются по их name атрибуту и ​​позволяют вам определять заполнители в вашем шаблоне, которые могут быть заполнены любым фрагментом разметки, который вы хотите, когда элемент используется в разметке. В shadow DOM <slot name="X"> определяет «точку вставки» – место, где отображаются элементы с slot="X". Затем браузер выполняет «композицию»: берёт элементы из обычного DOM-дерева и отображает их в соответствующих слотах теневого DOM-дерева. В результате мы получаем именно то, что хотели – компонент, который можно наполнить данными.
  • #32 Впервые поддрежка появилась в Chrome 33 под версией 0. однако в спецификацию версии 1 внесены важные поправки в API.
  • #35 the get() method of the CustomElementRegistry interface returns the constructor for a previously-defined custom element.