81
알아봅시다,

알아봅시다, Polymer: Web Components & Web Animations

Embed Size (px)

DESCRIPTION

GDG Korea WebTech : 시작하세요, Polymer, Oct, 11, 2014. Let's learn about specifications before diving into Polymer: - Web Components - Web Animations This slide includes resources from HTML5Rocks, Polymer and PolyTechnic.

Citation preview

Page 1: 알아봅시다, Polymer: Web Components & Web Animations

알아봅시다,

Page 2: 알아봅시다, Polymer: Web Components & Web Animations

+Changwook.Doh cwdoh.com

Page 3: 알아봅시다, Polymer: Web Components & Web Animations

Agenda

Page 4: 알아봅시다, Polymer: Web Components & Web Animations

§  Web Components §  Web Animations §  Web RTC §  Service Worker

Chrome Enchanted: “2014년 주목할만한 HTML5 규격 4종”

Page 5: 알아봅시다, Polymer: Web Components & Web Animations

Web Components

Page 6: 알아봅시다, Polymer: Web Components & Web Animations

어떤 문제들을 해결할 수 있을까?

Page 7: 알아봅시다, Polymer: Web Components & Web Animations

@polymer

#itshackademic

Page 8: 알아봅시다, Polymer: Web Components & Web Animations

Tab UI를 만드는 5가지 방법

Page 9: 알아봅시다, Polymer: Web Components & Web Animations

G-Mail 팀도 힘들어 하는 것?

TAG SOUP!!!

Page 10: 알아봅시다, Polymer: Web Components & Web Animations

http://drbl.in/esYL

Tab UI 정도는 좀 쉽게!

Page 11: 알아봅시다, Polymer: Web Components & Web Animations

무엇이 필요할까?

Page 12: 알아봅시다, Polymer: Web Components & Web Animations

“자주 사용되거나 구조적 분리가 필요한 요소를 다른 요소들과 충돌하지 않는 재활용 가능한 방법이 필요해요.”

Page 13: 알아봅시다, Polymer: Web Components & Web Animations

“특히 분리되어 있는 HTML, CSS, JS를 하나로 묶어 쉽게 불러들일 수 있으면...”

Page 14: 알아봅시다, Polymer: Web Components & Web Animations

<paper-tabs> <paper-tab>KNOWLEDGE</paper-tab> <paper-tab>HISTORY</paper-tab> <paper-tab>FOOD</paper-tab> </paper-tabs>

더 적은 코드. 덜 혼란스럽게.

Web Components

Page 15: 알아봅시다, Polymer: Web Components & Web Animations

Web Component?

Page 16: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports ●  HTML, CSS, JS를 로딩하고 싶다면?

Shadow DOM ●  캡슐화된 DOM, CSS의 스코프 분리

Template ●  드디어 등장한 네이티브로 지원되는 템플릿

Custom Element ●  새로운 엘리먼트의 정의. 기존 엘리먼트의 확장

Web Component를 지탱하는 4가지 규격!

Page 17: 알아봅시다, Polymer: Web Components & Web Animations

Custom Elements define new HTML/DOM elements

Page 18: 알아봅시다, Polymer: Web Components & Web Animations
Page 19: 알아봅시다, Polymer: Web Components & Web Animations

<paper-tabs selected=“1”> <paper-tab>Tab 1</paper-tab> <paper-tab>Tab 2</paper-tab> <paper-tab>Tab 3</paper-tab> </paper-tabs>

선언적, 가독성

직관적인 HTML

확장 방법의 일반화 → 재사용성

Custom Elements 새 HTML 엘리먼트의 정의

@polymer

#itshackademic

Page 20: 알아봅시다, Polymer: Web Components & Web Animations

Custom Elements 새 HTML 엘리먼트의 정의

var tabs = document.querySelector('paper-tabs'); tabs.addEventListener('core-activate', function() { console.log(this.selected); });

@polymer

#itshackademic

선언적, 가독성

직관적인 HTML

확장 방법의 일반화 → 재사용성

Page 21: 알아봅시다, Polymer: Web Components & Web Animations

// 새로운 엘리먼트의 등록var XFoo = document.registerElement('x-foo'); document.body.appendChild(new XFoo()); // 기존 엘리먼트로부터의 확장var MegaButton = document.registerElement('mega-button', { prototype: Object.create( HTMLButtonElement.prototype ) });

Custom Elements 새로운 엘리먼트의 등록과 기존 엘리먼트로부터의 확장

Page 22: 알아봅시다, Polymer: Web Components & Web Animations

var XFooProto = Object.create(HTMLElement.prototype);// x-foo에 foo() 메서드 추가XFooProto.foo = function() { alert('foo() called'); }; // read-only 속성의 "bar" 속성 정의Object.defineProperty(XFooProto, "bar", {value: 5}); // Element 등록var XFoo = document.registerElement('x-foo', {prototype: XFooProto}); // DOM 생성var xfoo = document.createElement('x-foo'); document.body.appendChild(xfoo);

Custom Elements 일반적인 사용 흐름

Page 23: 알아봅시다, Polymer: Web Components & Web Animations

var proto = Object.create(HTMLElement.prototype); proto.createdCallback = function() {...}; proto.attachedCallback = function() {…}; proto.detachedCallback = function() {…}; proto.attributeChangedCallback = function(attrName, oldValue, newValue) {…};var XFoo = document.registerElement('x-foo', {prototype: proto});

Callbacks Custom Elements

Page 24: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM DOM/CSS scoping

Page 25: 알아봅시다, Polymer: Web Components & Web Animations

<video src=“foo.webm” controls></video>

@polymer

#itshackademic

Page 26: 알아봅시다, Polymer: Web Components & Web Animations

<video src=“foo.webm” controls></video>

실제로 Shadow DOM

@polymer

#itshackademic

Page 27: 알아봅시다, Polymer: Web Components & Web Animations

<video src=“foo.webm” controls></video>

Page 28: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM Shadow Host & Shadow Root

Page 29: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM 101 ●  지정된 DOM을 정의한 DOM 트리로 렌더링

o  Shadow Host vs. Shadow Root o  DOM Visualizer

<div><h3>Light DOM</h3></div><script>var root = document.querySelector('div').createShadowRoot(); root.innerHTML = '<style>h3{ color: red; }</style>' + '<h3>Shadow DOM</h3>';</script>

Shadow DOM

Page 30: 알아봅시다, Polymer: Web Components & Web Animations

<style> :host { opacity: 0.4; transition: opacity 420ms ease-in-out; } :host(:hover) { opacity: 1; } :host(:active) { position: relative; top: 3px; left: 3px; }</style>

Shadow DOM Style

Page 31: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM 201 :host-context(.different) { color: red; }

:host(x-foo:host) { /* Applies if the host is a <x-foo> element.*/ } :host(x-bar:host) { /* Applies if the host is a <x-bar> element. */ } :host(div) { { /* Applies if the host element or an ancestor is a <div>. */ }

Shadow DOM Host 스타일

<body class="different"> <x-foo></x-foo></body>

Page 32: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM 201

<style> #host::shadow span { color: red; }</style><div id="host"> <span>Light DOM</span></div><script> var host = document.querySelector('div'); var root = host.createShadowRoot(); root.innerHTML = "<span>Shadow DOM</span>" + "<content></content>";</script>

Shadow DOM 외부에서 Shadow DOM 내부의 스타일링하기

Page 33: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM 201

// No fun. document.querySelector('x-tabs').shadowRoot .querySelector('x-panel').shadowRoot .querySelector('#foo');// Fun. document.querySelector('x-tabs:shadow x-panel::shadow #foo');

Shadow DOM ::shadow pseudo element

Page 34: 알아봅시다, Polymer: Web Components & Web Animations

Shadow DOM 201

x-tabs /deep/ x-panel { ... }

Shadow DOM /deep/ combinator

video /deep/ input[type="range"] { background: hotpink; }

Page 35: 알아봅시다, Polymer: Web Components & Web Animations

Templates native client-side templating

Page 36: 알아봅시다, Polymer: Web Components & Web Animations

var  compiled  =  _.template("hello:  <%=  name  %>");  

compiled({name:  'moe'});  

=>  "hello:  moe"  

<script type="text/template"> // ...

</script>

Text Templating

Offline DOM

Templating HTML Templates 이전

Script Overloading

<div id="mytemplate" hidden> <img src="logo.png"> <div class="comment"></div></div>

Page 37: 알아봅시다, Polymer: Web Components & Web Animations

<template> <div class=“comment”> <img src=“image.png”> </div> <script>...</script> </template>

DOM 구조를 위해 DOM 사용 → no XSS

복제/사용 전까지 콘텐츠는 비활성

doc fragment → 페이지와 분리됨

HTML Templates 네이티브로 구현된 클라이언트 기반의 템플릿

파싱되나, 렌더링되지 않음

1.  렌더링되지 않음 2.  스크립트는 실행되지 않음 3.  리소스(이미지, 오디오 등)는 로딩되지 않음 4.  문서 내에서 통상적인 DOM으로 액세스 불가

Page 38: 알아봅시다, Polymer: Web Components & Web Animations

HTML Templates 지원 여부 검사

function supportsTemplate() { return 'content' in document.createElement('template'); }if (supportsTemplate()) { // Good to go! } else { // Use old templating techniques or libraries. }

Page 39: 알아봅시다, Polymer: Web Components & Web Animations

HTML Templates 템플릿의 사용

<button onclick="useIt()">Use me</button><div id="container"></div> <script> function useIt() { var content = document.querySelector('template').content; content.querySelector('span').textContent = parseInt(span.textContent) + 1; document.querySelector('#container').appendChild( document.importNode(content, true)); }</script><template> <div>Template used: <span>0</span></div> <script>alert('Thanks!')</script></template>

Page 40: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports loading web components

Page 41: 알아봅시다, Polymer: Web Components & Web Animations

<script> var xhr = new XMLHttpRequest(); xhr.open('GET', '...', true); xhr.responseType = 'document'; xhr.onload = function(e) {}; xhr.send();

</script>

<iframe>

Script HACK!

Importing HTML Imports 이전

Ajax

<script type="text/html" src="..."></script>

Page 42: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports 무엇이던 불러오세요.

<head> <link rel="import" href="/path/to/imports/stuff.html"></head>

Page 43: 알아봅시다, Polymer: Web Components & Web Animations
Page 44: 알아봅시다, Polymer: Web Components & Web Animations
Page 45: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports 지원 여부 검사

function supportsImports() { return 'import' in document.createElement('link'); }if (supportsImports()) { // 지원하므로 그대로 진행합니다. } else { // 파일을 로딩하기 위한 다른 라이브러리나 require 시스템들을 사용하세요. }

Page 46: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports 이벤트 핸들링

<script async> function handleLoad(e) { console.log('Loaded import: ' + e.target.href); } function handleError(e) { console.log('Error loading import: ' + e.target.href); }</script><link rel="import" href="file.html" onload="handleLoad(event)" onerror="handleError(event)">

Page 47: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports 스크립트를 통한 Import

var link = document.createElement('link'); link.rel = 'import'; link.href = 'file.html' link.onload = function(e) {...}; link.onerror = function(e) {...}; document.head.appendChild(link);

Page 48: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports link.import

var content = document.querySelector('link[rel="import"]').import;

link.import == null ●  브라우저가 HTML Imports를 지원하지 않을 경우 ●  <link>가 rel="import"를 가지지 않을 경우 ●  <link>가 DOM에 추가되지 않은 경우 ●  <link>가 DOM으로부터 제거된 경우 ●  ‘CORS를 만족하는’ 리소스가 아닐 경우

Page 49: 알아봅시다, Polymer: Web Components & Web Animations

HTML Imports 콘텐츠의 삽입

<head> <link rel="import" href="warnings.html"></head><body> ... <script> var link = document.querySelector('link[rel="import"]'); var content = link.import; // Grab DOM from warning.html's document. var el = content.querySelector('.warning'); document.body.appendChild(el.cloneNode(true)); </script></body>

Page 50: 알아봅시다, Polymer: Web Components & Web Animations

Custom Elements 컴포넌트가 인터페이스를 가진 DOM Element 형태로 사용될 수 있도록...

Templates 컴포넌트의 골격이 사용하기 전까지 비활성화된 상태로 관리되도록...

Shadow DOM 컴포넌트의 스타일, DOM의 표현을 캡슐화하여 처리할 수 있도록...

HTML Imports 위의 요소들을 포함한 리소스(Markup, JS, CSS)를 로딩할 수 있도록...

웹 컴포넌트의 구성과 배포에 적합한 4가지 규격

Page 51: 알아봅시다, Polymer: Web Components & Web Animations

Browser support Summer 2014

Page 52: 알아봅시다, Polymer: Web Components & Web Animations

Further readings... Chrome Enchanted: 2014년 주목할만한 HTML5 규격 4종 웹 컴포넌트: 차세대 프론트엔드 웹 개발로 가는 관문 Introduction to Web Components Shadow DOM 101: 기초 Shadow DOM 201: CSS와 스타일링 Shadow DOM 301: 고급 개념과 DOM API HTML Imports: 웹을 위한 #include Custom Element: HTML에 새로운 엘리먼트를 정의하기 HTML의 새로운 템플릿 태그

Page 53: 알아봅시다, Polymer: Web Components & Web Animations

Web Animations

Page 54: 알아봅시다, Polymer: Web Components & Web Animations

CSS Transition ●  CSS3 규격의 일부로써, 지정된 CSS 속성 변경에 대한 전환 속도 제어

SVG Animation ●  SVG 기반의 애니메이션

requestAnimationFrame() ●  다음 Repaint 시점 이전 프레임 갱신이 가능하도록 콜백 제공

CSS Animation ●  CSS 기반의 키프레임 애니메이션

이미 존재하는 4가지 애니메이션 규격

Page 55: 알아봅시다, Polymer: Web Components & Web Animations

“이것으로 충분한가?”

Page 56: 알아봅시다, Polymer: Web Components & Web Animations

동기화

Playback - Seek, Pause, Reverse

CSS Animation/Transition Issues

시퀀싱(Sequencing)

Animation Blending

Debugging

Page 57: 알아봅시다, Polymer: Web Components & Web Animations

강력함

SVG Animation Issues

SVG에만 해당

Page 58: 알아봅시다, Polymer: Web Components & Web Animations

requestAnimationFrame()으로 렌더링 성능 저하 회피

Main UI 스레드 사용

JavaScript Animation Issues

보편성과 활용성 높음

CSS 스타일 조정(특히 inline style)으로 인한 Layouting, Recalculating, ... SVG 같은 직접 접근 불가능한 객체 존재

Page 59: 알아봅시다, Polymer: Web Components & Web Animations

Web Animations?

Page 60: 알아봅시다, Polymer: Web Components & Web Animations

Web Animations 1.0 HTML5에 추가된 새 애니메이션 규격

규격의 대상 ●  추상화된 애니메이션 모델 ●  JavaScript API

CSS 및 SVG 문법 및 기능 매핑은 포함하지 않음

Page 61: 알아봅시다, Polymer: Web Components & Web Animations

CSS 및 SVG 애니메이션을 위한 기반 모델 제공

하드웨어 가속 친화적!

Web Animations 1.0 HTML5에 추가된 새 애니메이션 규격

선언적인 형태, 하지만 JS API로 제공되는 애니메이션 기능!!!

Timeline, Sequence 등 애니메이션 동기화 API

동적인 애니메이션 조작성

Page 62: 알아봅시다, Polymer: Web Components & Web Animations

Web Animations 규격의 범위

Page 63: 알아봅시다, Polymer: Web Components & Web Animations

Editor’s Draft - http://w3c.github.io/web-animations/

Chrome - CSS Anim. 엔진 변경 V36 element.animate(), V38 Playback Control

Web Animations 표준화 및 브라우저 지원 등 주요 현황

선언적인 형태, 하지만 JS API로 제공되는 애니메이션 기능!!!

Firefox 및 Safari - 개발 중, Internet Explorer - 논의 중

web-animations.js Polyfill, Web Animations Demos

Page 64: 알아봅시다, Polymer: Web Components & Web Animations

규격

Page 65: 알아봅시다, Polymer: Web Components & Web Animations

<div class="pulse" style="width:150px;">Hello world!</div><script>

var elem = document.querySelector('.pulse');

var player = document.timeline.play(new Animation(elem, [

{opacity: "0.5", transform: "scale(0.5)"},

{opacity: "1.0", transform: "scale(1)"}

],

{

direction: "alternate", duration: 500, iterations: Infinity

}));</script>

Usage 자바스크립트 기바의 애니메이션

Page 66: 알아봅시다, Polymer: Web Components & Web Animations

Overview 웹 애니메이션의 모델

Timing Model ●  애니메이션 타이밍의 흐름(속도, 위치 등)을 제어

Animation Model ●  Timing Model에서 전달된 값을 기반으로 애니메이션 속성들에 대한 실제 값 적용

Page 67: 알아봅시다, Polymer: Web Components & Web Animations

Timing Model Timing Nodes

Page 68: 알아봅시다, Polymer: Web Components & Web Animations

Timing Model Inherited Time & Local Time

Page 69: 알아봅시다, Polymer: Web Components & Web Animations

Timing Group 애니메이션들에 대한 동기화 모델

Page 70: 알아봅시다, Polymer: Web Components & Web Animations

Sequence

Parallel group

Timing Group Mixin

Page 71: 알아봅시다, Polymer: Web Components & Web Animations

Animation Model Iteration & Duration

CSS Animation과의 차이점 ●  Iteration Duration = Active Duration / Iteration Count

Page 72: 알아봅시다, Polymer: Web Components & Web Animations

Animation Model 애니메이션의 시작 위치(1st Iteration)

Page 73: 알아봅시다, Polymer: Web Components & Web Animations

Web Animations API

Page 74: 알아봅시다, Polymer: Web Components & Web Animations

div class="pulse" style="width:150px;">Hello world!</div><script> var elem = document.querySelector('.pulse'); var player = document.timeline.play(new Animation(elem, [ {opacity: "0.5", transform: "scale(0.5)"}, {opacity: "1.0", transform: "scale(1)"} ], { direction: "alternate", duration: 0.5, iterations: Infinity }));</script>

애니메이션 생성 new Animation( target, props, time )

Page 75: 알아봅시다, Polymer: Web Components & Web Animations

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <path id=path d="M 100,100 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0"/> </defs></svg><script> var path = document.querySelector('#path'); var animFunc = new MotionPathEffect( path.pathSegList); var animation = new Animation(targetElement, animFunc, 2);</script>

모션 패스(Motion Path) new MotionPathEffect( path_list )

Page 76: 알아봅시다, Polymer: Web Components & Web Animations

타이밍 그룹(Timing Group) Sequencial/Parallel Group 생성

// Creating Parallel Groupvar parGroup = new ParGroup([new Animation(...), new Animation(...)]);// Creating Sequencial Groupvar seqGroup = new SeqGroup([new Animation(...), new Animation(...)]);// Creating Nested Groupsvar parGroup = new ParGroup([ new SeqGroup([ new Animation(...), new Animation(...), ]), new Animation(...)]);

Page 77: 알아봅시다, Polymer: Web Components & Web Animations

Player 각 애니메이션에 대한 컨트롤러

// starting animation & getting playervar player = document.timeline.play(myAnimation);// prop. example 2x speed up! player.playbackRate = 2;// animation control player.cancel(); player.finish(); player.play(); player.pause(); player.reverse();

Page 78: 알아봅시다, Polymer: Web Components & Web Animations

Custom Effect 타이밍 콜백에 의한 사용자화

function ( time, // Time Fraction interation, // Iteration Index target, // Target Element prevTime // Previous Time Fraction){ /* do stuff */}

Page 79: 알아봅시다, Polymer: Web Components & Web Animations

Browser support Oct. 2014

Page 80: 알아봅시다, Polymer: Web Components & Web Animations

Further readings... W3C Web Animations Specification Web Animations.js Polymer - Web Animations Web Animations Demo Web Animations - element.animate() is now in Chrome 36

Page 81: 알아봅시다, Polymer: Web Components & Web Animations

ROCK You!