Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Web Components: Um futuro cada vez mais presente!

Web Components: Um futuro cada vez mais presente!

Apresentação realizada no JS Day na cidade de Feira de Santana/Bahia no dia 06/Junho.

Jonata Weber

June 06, 2015
Tweet

More Decks by Jonata Weber

Other Decks in Programming

Transcript

  1. Web Components UM FUTURO CADA VEZ MAIS PRESENTE

  2. @jonataweber

  3. O que é Web Components

  4. Custom Elements HTML Templates Shadow DOM HTML Imports

  5. Por que investir em Web Components?

  6. –Michael Bleigh @ Founder of Divshot “Web Components represent the

    most important advancement in browser technology since AJAX”
  7. No início…

  8. <button>I'm a button!</button>

  9. User Experience

  10. None
  11. Hoje as coisas estão beeem diferentes…

  12. None
  13. Date Picker (HTML5) <input type="date">

  14. <video> (HTML5) <video src="video.mp4" controls autoplay></video>

  15. var map; function initialize() { var mapOptions = { zoom:

    8, center: new google.maps.LatLng(-34.397, 150.644) }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); Simple Google Map <body> <div id="map-canvas"></div> </body> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
  16. Quais as características de um componente?

  17. Componentes são encapsulados

  18. <select> <option>Small</option> <option>Medium</option> <option>Large</option> </select>

  19. Componentes são configuráveis

  20. <select id="size"> <option disabled>Small</option> <option disabled>Medium</option> <option selected>Large</option> </select>

  21. Componentes são combináveis

  22. <select> <optgroup label="German Cars"> <option>Mercedes</option> <option>Audi</option> </optgroup> ... </select>

  23. <google-map></google-map>

  24. <google-map latitude="-12.258940" longitude="-38.933655" zoom="10"></google-map>

  25. <google-map latitude="-12.258940" longitude="-38.933655" zoom="10"> <google-map-marker latitude="-12.258940" longitude="-38.933655" title="We are here!"></google-map-marker>

    </google-map>
  26. Como criar seus Web Components

  27. Web Components Custom Elements Shadow DOM HTML Templates HTML Imports

  28. Custom Elements possibilita criar seus próprios elementos 28

  29. Custom Elements 29 document.registerElement(‘jsday-fsa‘); <jsday-fsa></jsday-fsa> Depois utilize seu elemento HTML

  30. 30 LifeCycle • createdCallback() • attachedCallback() • detachedCallback() • attributeChangedCallback()

  31. Custom Elements 31 <jsday-fsa></jsday-fsa> var JsDay = Object.create(HTMLElement.prototype); JsDay.createdCallback =

    function() { this.textContent = 'JS Day - Feira de Santana'; }; document.registerElement('jsday-fsa', { prototype: JsDay });
  32. 32 Boas práticas! Custom Elements • Good • x-component •

    x-web-component • Bad • web_components • xelement • XElement
  33. Herança Elemento Nativo <button is="mega-button"> var MegaBtn = Object.create(HTMLElement.prototype); document.registerElement('mega-button',

    { prototype: MegaBtn, extends: 'button' }); …
  34. Herança Custom Element var XFooChild = Object.create(HTMLElement.prototype); document.registerElement(‘x-foo-child', { prototype:

    XFooChild, extends: ‘x-foo' }); … <x-foo is=“x-foo-child”></x-foo>
  35. Shadow DOM possibilita encapsular as implementações 35

  36. Shadow DOM <video> 36

  37. Shadow DOM <video> 37

  38. Shadow DOM 38 <h1>My Light DOM</h1> <div id="meu-elemento"></div> var el

    = document.querySelector('#meu-elemento'); var shadow = el.createShadowRoot(); var h1 = document.createElement(‘h1'); var style = document.createElement('style'); h1.textContent = 'Olá, JS DAY!'; style.innerHTML = 'h1 { color: red; }'; shadow.appendChild(h1); shadow.appendChild(style);
  39. Shadow DOM 39 <h1>My Light DOM</h1> <div id="meu-elemento"></div> var el

    = document.querySelector('#meu-elemento'); var shadow = el.createShadowRoot(); var h1 = document.createElement(‘h1'); var style = document.createElement('style'); h1.textContent = 'Olá, JS DAY!'; style.innerHTML = 'h1 { color: red; }'; shadow.appendChild(h1); shadow.appendChild(style);
  40. Estrutura de um Shadow DOM

  41. HTML Templates possibilita criar fragmento de código manipulável e não

    visível. 41
  42. <div id="template" style="display: none;"> <img src="logo.png" alt="Minha Logo"> </div> Templates

    (bad)
  43. <div id="template" style="display: none;"> <img src="logo.png" alt="Minha Logo"> </div> Templates

    (bad)
  44. HTML Template (good) 44 <template> <img src="success.jpg" alt="uma foto qualquer">

    </template> <button onclick="exibirFoto()">Exibir Foto</button> var t = document.querySelector('template').content; function exibirFoto() { document.body.appendChild(t.cloneNode(true)); }
  45. 45 var t = document.querySelector('template').content; function exibirFoto() { document.body.appendChild(t.cloneNode(true)); }

    <template> <img src="success.jpg" alt="uma foto qualquer"> </template> <button onclick="exibirFoto()">Exibir Foto</button> HTML Template (good)
  46. HTML Template nativo não tem data binding 46 // placeholders

    <template bind="{{items}}"></template> // repeaters <template repeat="{{item in items}}"></template> // conditionals <template if="{{item.active}}"></templat
  47. HTML Imports possibilita incluir e reutilizar documentos HTML em outros

    documentos HTML 47
  48. <!DOCTYPE html> <html> <head> <title>PHP Includes</title> </head> <body> <?php include

    'header.php' ?> <div>Meu Conteúdo</div> <?php include 'footer.php' ?> </body> </html> PHP Includes
  49. HTML Imports <link rel="import" href="cabecalho.html">

  50. HTML Imports <link rel="import" href="cabecalho.html"> index.html <div id="template"> <h1>Olá, JS

    DAY!</h1> <h2>Esse é o cabeçalho do site!</h2> </div> <style> h1 { color: red; } </style> cabecalho.html var link = document.querySelector('link[rel=import]'); var importDoc = link.import; var template = importDoc.querySelector('#template'); var style = importDoc.querySelector('style'); document.body.appendChild(template.cloneNode(true)); document.head.appendChild(style.cloneNode(true));
  51. Custom Elements Permite criar novas elementos HTML e extender os

    componentes nativos HTML Templates Possibilita criar fragmento de código manipulável e não visível pelo browser Shadow DOM Encapsulamento e escopo CSS HTML Imports Ajuda a “empacotar" e carrega o componente
  52. http://jonrimmer.github.io/are-we-componentized-yet/

  53. http://status.modern.ie Suporte no IE

  54. Polyfill Implementa a tecnologia que um desenvolvedor espera que o

    navegador forneça nativamente
  55. Polyfill Implementa a tecnologia que um desenvolvedor espera que o

    navegador forneça nativamente webcomponents.js
  56. Usando Polyfills

  57. www.polymer-project.org Polymer 1.0

  58. Polymer Elements Polymer Polyfill (webcomponents.js) Native Camadas do Polymer

  59. Installing Polymer $ bower install polymer

  60. https://developers.google.com/web/tools/polymer-starter-kit/ Polymer Boilerplate

  61. Criando um Polymer element 1. Importar o Polymer core (polymer.html)

    2. Declarar seu elemento usando <dom-module> 3. Inicializar o seu elemento usando Polymer({is: "my-element"}); <link rel="import" href="../bower_components/polymer/polymer.html"> <dom-module id="my-element"> <template> <span>Hello from <b>my-element</b>. This is my Shadow DOM.</span> </template> </dom-module> <script> Polymer({is: "my-element"}); </script>
  62. PROCURAR $ bower install Polymer/core-toolbar $ bower install Polymer/core-icon-button #jsdayfsa

  63. IMPORTAR <head> <link rel="import" href="core-toolbar.html"> <link rel="import" href="core-icon-button.html"> </head> #jsdayfsa

  64. USE <core-toolbar> <core-icon-button icon="menu"></core-icon-button> <span flex>Toolbar</span> <core-icon-button icon="refresh"></core-icon-button> <core-icon-button icon="add"></core-icon-button>

    </core-toolbar> #jsdayfsa
  65. USE <core-toolbar> <core-icon-button icon="menu"></core-icon-button> <span flex>Toolbar</span> <core-icon-button icon="refresh"></core-icon-button> <core-icon-button icon="add"></core-icon-button>

    </core-toolbar> #jsdayfsa
  66. “There's an element for that!”

  67. elements.polymer-project.org Polymer Catalog

  68. customelements.io

  69. bit.ly/1BeBJ9d

  70. bower.io

  71. webcomponents.org

  72. <!-- Polyfill Web Components support for older browsers --> <script

    src="bower_components/webcomponentsjs/ webcomponents.js"></script> <!-- Import element --> <link rel="import" href="meu-contador/meu-contador.html"> <!-- Use element --> <meu-contador pontos="50"></meu-contador> meu-contador github.com/jonataa/custom-elements
  73. github.com

  74. <!-- Polyfill Web Components support for older browsers --> <script

    src=“/bower_components/webcomponentsjs/webcomponents.js"></ script> <!-- Import element --> <script src="/bower_components/time-elements/time-elements.js"></ time <time is="time-ago" datetime="2014-07-04T16:30:00-08:00"></time>
  75. None
  76. x-tags

  77. bit.ly/1vtuetm

  78. None
  79. React.js NÃO utiliza as especificações!

  80. Mederi Saúde Domiciliar

  81. https://translate.google.com/community

  82. https://play.google.com/music

  83. buitwithpolymer.org

  84. Image: bit.ly/1rUNnpd Vamos componentizar a Web!

  85. Obrigado! [email protected] @jonataweber github.com/jonataa