Developing Web Components Although web components are still on the bleeding edge—barely “ With this book, Jarrod D supported in modern browsers—the technology is also moving extremely and Jason make web e fast. This practical guide gets you up to speed on the concepts underlying v components accessible W3C’s emerging standard and shows you how to build custom, reusable e HTML5 Web Components. to a large number of l o developers. The sections Regardless of your experience with libraries such as jQuery and Polymer, p this book teaches JavaScript developers the DOM manipulations these on custom elements i n libraries perform. You’ll learn how to build a basic widget with vanilla and shadow DOM Developing JavaScript and then convert it into a web component that’s semantic, g will help solidify your declarative, encapsulated, consumable, and maintainable. With custom W understanding of new components, the Web can finally fulfill its potential as a natively extensible application platform. This book gets you in at the right time. web platform features e for composition and b Web ■ Understand core concepts (such as normal flow and encapsulation, helping positioning, and z-index) for properly positioning, dragging, C and resizing elements you build more robust o ■ Explore UI concepts and patterns typically abstracted away by components and apps.” m Dojo, jQuery UI, Kendo UI, and other libraries —Addy Osmani p Components engineer focusing on Chrome ■ Dive into the W3C standard and convert your working widget and Polymer at Google o example into a fully functioning web component n ■ Learn how to encapsulate, package, and deploy your web “ I'm really excited that e components with Google’s Polymer framework Jarrod and Jason have put n together this book to help t s Jarrod Overson has been developing on the Web for over 15 years for startups guide new developers and and global companies alike. Currently at Shape Security, Jarrod is an active pro- UI FROM JQUERY TO POLYMER get them started down the ponent and contributor to open source and JavaScript language tooling; he’s cre- ated Plato and many other tools and libraries. path of componentizing Jason Strimpel is a software engineer with over 15 years experience developing the Web!” web applications. He’s currently employed at WalmartLabs where he writes soft- ware to support UI application development. Jason is also an active member of —Rob Dodson the open source community managing projects such as LazoJS. Developer Advocate at Google & SO trv ime r pso en WEB PROGRAMMING Twitter: @oreillymedia l facebook.com/oreilly US $29.99 CAN $34.99 ISBN: 978-1-491-94902-3 Jarrod Overson & Jason Strimpel Developing Web Components Although web components are still on the bleeding edge—barely “ With this book, Jarrod D supported in modern browsers—the technology is also moving extremely and Jason make web e fast. This practical guide gets you up to speed on the concepts underlying v components accessible W3C’s emerging standard and shows you how to build custom, reusable e HTML5 Web Components. to a large number of l o developers. The sections Regardless of your experience with libraries such as jQuery and Polymer, p this book teaches JavaScript developers the DOM manipulations these on custom elements i n libraries perform. You’ll learn how to build a basic widget with vanilla and shadow DOM Developing JavaScript and then convert it into a web component that’s semantic, g will help solidify your declarative, encapsulated, consumable, and maintainable. With custom W understanding of new components, the Web can finally fulfill its potential as a natively extensible application platform. This book gets you in at the right time. web platform features e for composition and b Web ■ Understand core concepts (such as normal flow and encapsulation, helping positioning, and z-index) for properly positioning, dragging, C and resizing elements you build more robust o ■ Explore UI concepts and patterns typically abstracted away by components and apps.” m Dojo, jQuery UI, Kendo UI, and other libraries —Addy Osmani p Components engineer focusing on Chrome ■ Dive into the W3C standard and convert your working widget and Polymer at Google o example into a fully functioning web component n ■ Learn how to encapsulate, package, and deploy your web “ I'm really excited that e components with Google’s Polymer framework Jarrod and Jason have put n together this book to help t s Jarrod Overson has been developing on the Web for over 15 years for startups guide new developers and and global companies alike. Currently at Shape Security, Jarrod is an active pro- UI FROM JQUERY TO POLYMER get them started down the ponent and contributor to open source and JavaScript language tooling; he’s cre- ated Plato and many other tools and libraries. path of componentizing Jason Strimpel is a software engineer with over 15 years experience developing the Web!” web applications. He’s currently employed at WalmartLabs where he writes soft- ware to support UI application development. Jason is also an active member of —Rob Dodson the open source community managing projects such as LazoJS. Developer Advocate at Google & SO trv ime r pso en WEB PROGRAMMING Twitter: @oreillymedia l facebook.com/oreilly US $29.99 CAN $34.99 ISBN: 978-1-491-94902-3 Jarrod Overson & Jason Strimpel Developing Web Components Jarrod Overson and Jason Strimpel Developing Web Components by Jarrod Overson and Jason Strimpel Copyright © 2015 Jarrod Overson and Jason Strimpel. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Simon St.Laurent and Brian Anderson Indexer: Wendy Catalano Production Editor: Colleen Lobner Interior Designer: David Futato Copyeditor: Rachel Head Cover Designer: Ellie Volckhausen Proofreader: Charles Roumeliotis Illustrator: Rebecca Demarest February 2015: First Edition Revision History for the First Edition 2015-02-06: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491949023 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Developing Web Components, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-94902-3 [LSI] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What Are Web Components? 2 HTML Templates 3 HTML Imports 3 Custom Elements 4 The Shadow DOM 4 Why Web Components? 4 Part I. UI Core Concepts 2. Creating a Solid Foundation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 The Importance of a DOM Abstraction Layer 11 API Design and Widget Life Cycle 12 The Inheritance Pattern 14 Dependencies 15 Optimization 16 A Web Component Is Not JavaScript Alone 17 Example Widget 18 The Voltron Widget Base Class 18 Dialog Class 20 Dialog CSS and HTML 21 Summary 22 3. Normal Flow and Positioning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Normal Flow 23 iii Positioning Elements 24 offsetParent 25 Positioning 26 Calculating an Element’s Position 29 Relative to the Viewport 29 Relative to the Document 30 Positioning the Dialog Widget 31 Summary 31 4. Understanding and Managing z-index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 What Exactly Is the z-index Property? 33 Rendering Layers, Stacking Order, and z-index 34 Default Stacking Orders 34 Overriding the Default Stacking Order 35 Stacking Contexts 36 How Is a Stacking Context Created? 36 Increasing Complexity 37 Managing z-indexes 37 z-index Manager 38 Converting to a jQuery Plugin 45 Adding z-index Management to the Dialog Widget 47 Summary 47 Part II. Building Our UI 5. Cloning Nodes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Using the cloneNode Method 52 Using jQuery.clone 53 Continuation of the Dialog Widget 55 Summary 55 6. Constructing an Overlay. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Defining an API 57 Utilities 59 Detecting Scrollbar Width 59 Accounting for the Scrollbar When Calculating a Containing Element’s Width 60 Getting an Element’s Dimensions and Coordinates 61 Listening for Resize and Scrolling Events 62 Updating Options 62 Destroying 63 iv | Table of Contents Positioning 63 Positioning an Element Relative to the Viewport or Another Element 64 Positioning an Element Relative to Another Element 66 Adding the Overlay to the Dialog Widget 68 Summary 69 7. Making Elements Draggable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Mouse Events 71 $.mousemove 71 $.mousedown 72 $.mouseup 72 Mouse Events Best Practices 72 1. Bind $.mousemove on $.mousedown 72 2. Unbind $.mousemove on $.mouseup 73 3. Bind $.mouseup to the <body> 73 4. Namespace All Event Bindings 73 Defining an API 73 Creating a Drag Handle 74 Making Things Move 75 $.mousedown Handler 75 $.mousemove Handler 76 $.mouseup Handler 77 Destroying a Draggable Instance 78 Making the Dialog Widget Draggable 78 Summary 79 8. Resizing Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Mouse Events and Best Practices (Recap) 81 Events 81 Best Practices 82 Resizing an Element 82 Making a Resizable API 83 Defining Drag Handles 84 Binding Event Handlers 85 $.mousedown Handler 85 $.mousemove Handler 87 $.mouseup Handler 87 Destroying a Resizable Instance 88 Completed Resizing Library 88 Making the Dialog Widget Resizable 92 Summary 94 Table of Contents | v 9. Completing the Dialog Widget. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Styling the Widget 95 Adding CSS 95 Concatenating the JavaScript 96 Summary 97 Part III. Building HTML5 Web Components 10. Utilizing Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Understanding the Importance of Templates 102 Deferring the Processing of Resources 102 Deferring the Rendering of Content 102 Hiding the Content from the DOM 103 Creating and Using a Template 103 Detecting Browser Support 103 Placing a Template in Markup 103 Adding a Template to the DOM 104 Converting the Dialog Component to a Template 104 Creating a Wrapper API for the Dialog Template 105 Instantiating a Dialog Component Instance 106 Abstracting the Dialog Template Wrapper 106 Summary 107 11. Working with the Shadow DOM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 What Is the Shadow DOM? 109 Shadow DOM Basics 110 Shadow Host 110 Shadow Root 110 Using a Template with the Shadow DOM 111 Shadow DOM Styling 112 Style Encapsulation 112 Styling the Host Element 113 Styling Shadow Root Elements from the Parent Page 115 Content Projection 117 Projection via a Content Tag 117 Projection via Content Selectors 118 Getting Distributed Nodes and Insertion Points 119 Shadow Insertion Points 120 Events and the Shadow DOM 122 Updating the Dialog Template to Use the Shadow DOM 122 Dialog Markup 123 vi | Table of Contents Dialog API 124 Updating the Dialog show Method 124 Instantiating a Dialog Component Instance 125 Summary 125 12. Creating Custom Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Introducing Custom Elements 128 Registering Custom Elements 128 Extending Elements 129 Extending Custom Elements 129 Extending Native Elements 130 Defining Properties and Methods 130 Resolving Custom Elements 131 Hooking Into Custom Element Life Cycles 131 createdCallback 132 attachedCallback 132 detachedCallback 132 attributeChangedCallback 133 Styling Custom Elements 133 Utilizing Templates and the Shadow DOM with Custom Elements 134 Converting the Dialog Component to a Custom Element 135 Creating the Dialog Custom Element 136 Implementing the Dialog Custom Element’s Callbacks 136 Implementing the Dialog Custom Element API 137 Showing the Dialog 138 Summary 138 13. Importing Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Declaring an Import 139 Accessing an Import’s Content 140 Referencing Documents 141 Applying Styles 142 Accessing Templates 143 Executing JavaScript 144 Understanding Imports in Relation to the Main Document 144 Parsing Imports 144 Cross-Domain Considerations 145 Subimports 145 Loading Custom Elements 145 Importing the Dialog 146 Summary 147 Table of Contents | vii Part IV. Testing, Building, and Deploying Components with Polymer 14. Introducing Polymer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Polymer Elements 154 Adding Style 156 External Resources 157 Filtering Expressions 157 Template Syntax 159 Data Binding 159 Block Repetition 159 Bound Scopes 160 Conditional Blocks 160 Multiple Template Directives at Once 161 Attributes and Properties—Your Element’s API 161 Naked Attributes 161 Published Properties 162 Instance Methods 162 Polymer’s JavaScript APIs 163 Life Cycle Methods 163 Events 164 Managing Delayed Work 164 Summary 165 15. Porting Our Dialog to Polymer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Why Port Anything to Polymer at All? 168 The Direct Port 169 Managing Dependencies 169 Installing Dependencies with Bower 171 Getting Started 173 That Was Easy—A Little Too Easy! 182 jQuery in a Polymer World 182 What Does jQuery Provide? 183 Removing jQuery 183 The Verdict on jQuery 186 Summary 187 16. Testing Web Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 PhantomJS 1 190 PhantomJS 2 191 Selenium WebDriver 191 Karma 191 viii | Table of Contents