Skip to content

Web

Polymer 2.0 文档笔记(2) ShadowDOM

ShadowDOM API

var div = document.createElement('div'); 
var shadowRoot = div.attachShadow({mode: 'open'}); 
shadowRoot.innerHTML = '<h1>Hello Shadow DOM</h1>';

ShadowDOM Composition

主要概念:

  • LightDOM: 元素的实际子孙节点,浏览器不会对LightDOM做任何的修改和移动。但是渲染的时候会渲染到相对于的slot节点之下,如果找不到对应的slot节点,则不会渲染。
  • ShadowDOM: 不解释。。。
  • Slot: slot标签是LightDOM插入到ShadowDOM中的标记。可以设置name属性来匹配对应的LightDOM。Slot标签不会渲染,但是还是会存在(即能够参与事件传递)。另外如果一个LightDOM找不到匹配的slot插入点,则改LightDOM也不会被渲染。
  • Flatterned Tree: LightDOM通过ShadowDOM里面的slot标记合并在一起(flattern)的抽象的DOM树(devTools中不可见),是最后浏览器实际用来渲染的DOM树。

需要注意的是:

Slots can only be selected explicitly, by slot name. It's impossible to select content implicitly, based on a tag name or an arbitrary selector like :not(.header).

slot只能用slot name来区分、选中。不能用其他任意的css选择器。

各个slot之间的区域是互斥的,而且 只能选择top-level元素 (包括后面的::slotted(selector)选择器)。

<!-- shadow DOM v1 template -->
<template>
  <!-- this slot gets any top-level nodes that don't have slot
       attributes. -->
  <slot></slot>
  <!-- the following insertion point gets any top-level nodes that have
       slot="special". -->
  <slot name="special"></slot>
  <!-- top-level nodes that have slot attributes with other values
       don't get distributed at all. -->
</template>

Fallback content

实际上就是可以在模版的slot里面写东西,作为一个默认值

Mulit-level distribution

多级slot嵌套。flatterning的时候规则是从外向里, 因此父节点的slot下面的lightDOM会渲染在子节点的LightDOM之下。

Slot APIs && Observe added and removed children

  • HTMLElement.assignedSlot
  • HTMLSlotElement.assignedNodes
  • HTMLSlotElement.slotchange(event)
  • Polymer.FlattenedNodesObserver
  • Polymer.FlattenedNodesObserver.getFlattenedNodes(node)
  • new Polymer.FlattenedNodesObserver(this.$.slot,(info)=>{})

详情参考https://www.polymer-project.org/2.0/docs/devguide/shadow-dom

Shadow DOM polyfills

因为shadowDOM不是每个浏览器都支持,所以使用了webcomponents.js中的shadyDOM和shadyCSS两个polyfills。

How the polyfills work

The polyfills use a combination of techniques to emulate shadow DOM: Shady DOM: Maintains the logical divisions of shadow tree and descendant tree internally, so children added to the light DOM or shadow DOM render correctly. Patches DOM APIs on affected elements in order to emulate the native shadow DOM APIs. Shady CSS: Provides style encapsulation by adding classes to shadow DOM children and rewriting style rules so that they apply to the correct scope.

ShadyDOM

ShadyDOM主要原理是patch原生DOM API来提供跟native shadowDOM一致的接口。在内存中维护了一个保存LightDOM的children树和一个保存ShadowDOM的ShadowRoot树。但是实际上元素下面就是一颗渲染好的flatterned树。因为这个是就是实际上的用来渲染的树,所以不存在slot,因此shadyDOM polyfills方案里面的slot元素不参与事件传递。

ShadyCSS

ShadyCSS主要提供了原生ShadowDOM规则的支持和两个cssnext特性:CSS custom propertiescustom property mixins. Scoped CSS特性的实现原理跟Vue相似:对元素的ShadowDOM添加class,并重写CSS的匹配规则。

ShadowDOM styling

ShadowDOM样式三大原则:

  1. 外层的样式不会对内层样式进行匹配。
  2. 内层样式不会影响外层样式。
  3. 可继承的css属性(例如:color)等,内层可以照样继承自外层。

两个特殊伪类: - 选择ShadowDOM的根节点节点:host/:host(selector)

#shadow-root
  <style>
    /* custom elements default to display: inline */
    :host {
      display: block;
    }
    /* set a special background when the host element
       has the .warning class */
    :host(.warning) {
      background-color: red;
    }
  </style>

  • 选择分布式节点——::slotted()
  • slotted()选择器右边不能写任何其他选择器。
  • slotted(selector) 里面的selector只能是简单选择器,并且只能选择顶级元素。
  • slotted(*) 选择默认的LightDOM(不包含有name值的slot)
  • slotted(slot=tkw) 选择name为tkw的LightDOM
<dom-module>
<template>
  <style>
    ::slotted(img){ 
      border-radius: 103%;
    }
  </style>
  <div><slot></slot></div>
</template>
<script>
  // define the element's class element
  class XFoo extends Polymer.Element {
    // 'is' getter, return the tag name which is lowercased. required.
    static get is(){
      return 'x-foo';
    }
    // Define the properties.
    static get properties() {}
    // Element class can define custom element reactions
    constructor() { super(); }
    connectedCallback() {
      super.connectedCallback();
      console.log('x-foo created!');
    }
  }

  window.customElements.define(XFoo.is, XFoo);
</script>
</dom-module>

<x-foo>
  <h1>A logo</h1>
  <img />
</x-foo>

Share styles between elements

<dom-module id="my-style-module"> 
  <template> 
    <style> 
      <!-- Styles to share go here! --> 
    </style> 
  </template> 
</dom-module>

<!-- another element -->
<dom-module id="new-element"> 
  <template> 
    <style include="my-style-module"> 
      <!-- Any additional styles go here --> 
    </style> 
    <!-- The rest of your element template goes here --> 
  </template> 
</dom-module>

custom-style

兼容性写法,使用<custom-style>标签包围main document里面的全局<style>能避免在不支持shadowDOM v1规范的浏览器中全局css规则继续在shadowDOM中生效。 注意是避免CSS规则生效,而不是避免CSS样式的继承 custom-style元素不包含在Polymer中,需要引入:

<link rel="import" href="components/polymer/lib/elements/custom-style.html">

CSS custom properties

主要是提供一个支持两个CSS Next语法的扩展版本:

custom properties & var()
  • 可以通过——customvar形式定义变量,然后通过var(--customvar,[defaultvar])取值。
  • 通过这个特性我们可以暴露出一些可配置的变量,然后供组件外部的父元素进行自定义。
  • 与cssnext规范不同的是,cssnext的变量定义必须写在:root{}中,而Polymer则是不能在LightDOM中使用。
p {
  color: var(--paper-red-500);
}
paper-checkbox {
  --paper-checkbox-checked-color: var(--paper-red-500);
}

custom properties set & @apply

Polymer默认不支持自定义属性集合,需要手动引入:

<!-- import CSS mixins polyfill -->
<link rel="import" href="/bower_components/shadycss/apply-shim.html">
相当于cssnext对应的语法,但是同样可以在任何css Rule下使用。
<dom-module id="my-element"> 
  <template> 
    <style> 
      /* Apply custom theme to toolbars */ 
      :host { 
        --my-toolbar-theme: { 
          background-color: green; 
          border-radius: 4px; 
          border: 1px solid gray; 
        }; 
        --my-toolbar-title-theme: { 
          color: green; 
        }; 
      } 
      /* Make only toolbars with the .warning class red and bold */ 
      .warning { 
        --my-toolbar-title-theme: { 
          color: red; 
          font-weight: bold; 
        }; 
      } 
    </style> 
    <my-toolbar title="This one is green."></my-toolbar> 
    <my-toolbar title="This one is green too."></my-toolbar> 
    <my-toolbar class="warning" title="This one is red."></my-toolbar> 
  </template> 
  <script> 
    class MyElement extends Polymer.Element { 
      static get is() { 
        return "my-element"; 
      } 
    } 
    customElements.define(MyElement.is, MyElement); 
  </script> 
</dom-module> 

<dom-module id="my-toolbar"> 
  <template> 
    <style> 
      :host { 
        padding: 4px; 
        background-color: gray; 
        /* apply a mixin */ 
        @apply --my-toolbar-theme; 
      } 
      .title { 
        @apply --my-toolbar-title-theme; 
      } 
    </style> 
    <span class="title">{{title}}</span> 
  </template> 
  ... 
</dom-module>

CSS Custom Property API

updateStyles

动态更改css自定义属性的值。

<dom-module id="x-custom">
  <template>
    <style>
      :host {
        --my-toolbar-color: red;
      }
    </style>
    <my-toolbar>My awesome app</my-toolbar>
    <button on-tap="changeTheme">Change theme</button>
  </template>
  <script>
    class XCustom extends Polymer.Element {
      static get is() {
        return "x-custom";
      }
      static get changeTheme() {
        return function() {
        this.updateStyles({
          '--my-toolbar-color': 'blue',
        });
      }
    }
    customElements.define(XCustom.is, XCustom);
  </script>
</dom-module>
注意当外层元素或者被继承元素里面已经定义了一个变量,那么当前再定义这个变量是无效的,需要手动调用该方法。这个行为类似于Less

getComputedStyle(ShadyCSS.getComputedStyle)

获得当前自定义属性的值(需要区分原生和Polyfill)

if (ShadyCSS) { 
  style = ShadyCSS.getComputedStyleValue('--something'); 
} else { 
  style = getComputedStyle(this, '--something'); 
} 

DOM Templating

By default, adding a DOM template to an element causes Polymer to create a shadow root for the element and clone the template into the shadow tree.

DOMTemplate是通过clone操作添加到shadow tree里面去的。 有三种方式定义一个DOM Template:

template标签

直接将模板写在<template>标签里面, 是最直接的方式、最常见的方式。

<dom-module id="x-foo"> 
<template>I am x-foo!</template> 
<script> 
    class XFoo extends Polymer.Element { 
      static get is() { return  'x-foo' } 
    } 
    customElements.define(XFoo.is, XFoo); 
</script> 
</dom-module> 

String template

字符串模板

class MyElement extends Polymer.Element { 

static get template() { 
    return `<style>:host { color: blue; }</style> 
       <h2>String template</h2> 
       <div>I've got a string template!</div>` 
  } 
} 
customElements.define('my-element', MyElement); 

Retrieve or generate your own template element

通过继承或手动实现template getter获得模板. 注意: 1. 不要对父类的template直接修改,应该先拷贝一份出来。 2. 如果需要做一些耗资源的操作,应该对你修改的template进行缓存,以免重复调用。

(function() { 
  let memoizedTemplate; 

class MyExtension extends MySuperClass { 
    static get template() { 
      if (!memoizedTemplate) { 
        // create a clone of superclass template (`true` = "deep" clone) 
        memoizedTemplate = MySuperClass.template.cloneNode(true); 
        // add a node to the template. 
        let div = document.createElement('div'); 
        div.textContent = 'Hello from an extended template.' 
        memoizedTemplate.content.appendChild(div); 
      } 
      return memoizedTemplate; 
    } 
  } 

})(); 

URLs in template

默认对于所有从其他文件里面引入的组件里面元素所包含的链接Polymer是不做处理的,所有的相对路径的资源最后都是相对于主文档(main document)的路径。 但是我们可以使用下面两个特殊的标记

importPath

A static getter on the element class that defaults to the element HTML import document URL and is overridable. It may be useful to override importPath when an element's template is not retrieved from a  or the element is not defined using an HTML import.

一个静态getter函数,默认指向该元素被HTML import时候的URL,也可以被重写。

rootPath

An instance property set to the value of Polymer.rootPath which is globally settable and defaults to the main document URL. It may be useful to set Polymer.rootPath to provide a stable application mount path when using client side routing.

一个实例化的属性,值被设置为Polymer.rootPath。代表着主文档(main document)的URL。

Relative URLs in styles are automatically re-written to be relative to the importPath property. Any URLs outside of a <style> element should be bound using importPath or rootPath where appropriate.

所有style标签里面的URL全部被重写为相对于importPath的路径。除此之外,都需要自己手动添加合适的前缀:

<img src$="[[importPath]]checked.jpg"> 

<a href$="[[rootPath]]users/profile">View profile</a>

Static node map

Polymer builds a static map of node IDs when the element initializes its DOM template, to provide convenient access to frequently used nodes without the need to query for them manually. Any node specified in the element's template with an id is stored on the this.$ hash by id. The this.$ hash is created when the shadow DOM is initialized. In the ready callback, you must call super.ready() before accessing this.$.

这个主要是Polymer提供的一个可以快速访问DOM节点的方式。可以通过this.$[id]来获取拥有对应id的元素/自定义元素。
相当于document.getElementById的升级版类似于react中的this.refs
this.$接口只能在ready回调函数的super.ready()之后被调用。
动态创建的节点(dom-repeat dom-if)并不包含在this.$集合里,但是还是可以用标准的querySelector方法获取。

<dom-module id="x-custom"> 

<template> 
    Hello World from <span id="name"></span>! 
  </template> 

<script> 
    class MyElement extends Polymer.Element { 
      static get is() { return  'x-custom' } 
      ready() { 
        super.ready(); 
        this.$.name.textContent = this.tagName; 
      } 
    } 
  </script> 

</dom-module>

Polymer 2.0 文档笔记(1) Custom Elements

https://www.polymer-project.org/2.0/docs/devguide/custom-elements

Custom element names. By specification, the custom element's name must start with a lower-case ASCII letter and must contain a dash (-). There's also a short list of prohibited element names that match existing names. For details, see the Custom elements core concepts section in the HTML specification.

自定义元素的命名规则: 按照规范,自定义元素的命名中必须以一个小写字母开始,必须包含一个连接符(-)

Custom properties can only be defined in rule-sets that match the html selector or a Polymer custom element. This is a limitation of the Polymer implementation of custom properties.

Polymer实现方式的局限: 只有html元素或者Polymer自定义元素才能使用自定义CSS属性。(个人感觉虽然shadowDOM原生支持CSS隔离,但是一部分元素能用cssnext一部分元素不能用,割裂感太严重了。)

Polymer does not currently support extending built-in elements. The custom elements spec provides a mechanism for extending built-in elements, such as <button> and <input>. The spec calls these elements customized built-in elements. Customized built-in elements provide many advantages (for example, being able to take advantage of built-in accessibility features of UI elements like <button> and<input>). However, not all browser makers have agreed to support customized built-in elements, so Polymer does not support them at this time.

因为浏览器厂商的争议,Polymer不支持扩展内建元素。

在生产环境下main document不要定义自定义元素。基于实验目的可以使用 HTMLImports.whenReady(callback)方法等待所有html import 加载完毕。

组件生命周期

标准的几个生命周期回调:

Reaction Description
constructor Called when the element is upgraded (that is, when an element is created, or when a previously-created element becomes defined).
connectedCallback Called when the element is added to a document.
disconnectedCallback Called when the element is removed from a document.
attributeChangedCallback Called when any of the element's attributes are changed, appended, removed, or replaced,

For each reaction, the first line of your implementation must be a call to the superclass constructor or reaction.

开始写自己的回调事件之前都必须先调用super上面的回调。Super.connectedCallback();  

The constructor can't examine the element's attributes or children, and the constructor can't add attributes or children.

Constructor函数中不能对DOM进行任何操作。

In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice. In general, the constructor should be used to set up initial state and default values, and to set up event listeners and possibly a shadow root.

https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance

Constructor里面只应该做一些初始化状态、值、绑定事件,建立shadowroot之类的工作。其他工作应该推迟到connectedCallback里面做,但是需要注意的是__connectedCallback可能会调用多次__。

The custom elements specification doesn't provide a one-time initialization callback. Polymer provides a readycallback, invoked the first time the element is added to the DOM.

Polymer提供了一个规范里面没有的回调: Ready, 只在元素第一次加入DOM时候触发。

ready() { 
  super.ready(); 
  // When possible, use afterNextRender to defer non-critical 
  // work until after first paint. 
  Polymer.RenderStatus.afterNextRender(this, function() { 
    ... 
  }); 
} 

Elements have a custom element state that takes one of the following values:

  1. uncustomized: The element does not have a valid custom element name. It is either a built-in element (<p>, <input>) or an unknown element that cannot become a custom element (<nonsense>)
  2. undefined: The element has a valid custom element name (such as "my-element"), but has not been defined.
  3. custom: The element has a valid custom element name and has been defined and upgraded.
  4. failed: An attempt to upgrade the element failed (for example, because the class was invalid).

元素内部拥有四个状态,我们不能直接获得,但是可以使用:defined伪类来选择"uncustomized"和"custom"的元素。

自定义元素

Hybrid elements: should continue to use the Polymer DOM APIs, but may require some changes. Legacy elements: can use the Polymer DOM APIs or the native DOM APIs. Class-based elements: should use native DOM APIs.

总共有三种自定义元素:

  • Hybird element: 主要是为了兼容Polymer 1.x;但 Gesture Events只支持Hybird elements。详见下文。
  • Legacy element:处于两者之间(没有看出有什么用处)
  • Class-based element:Polymer 2.0 最常用的自定义元素方式。
Class-based elements
// define the element's class element
class MyElement extends Polymer.Element {
  // 'is' getter, return the tag name which is lowercased. required.
  static get is(){
    return 'my-element';
  }
  // Define the properties.
  static get properties() {}
  // Element class can define custom element reactions
  constructor() { super(); }
  connectedCallback() {
    super.connectedCallback();
    console.log('my-element created!');
  }
  ready() {
    super.ready();
    this.textContent = 'I\'m a custom element!';
  }
}

// Associate the new class with an element name
customElements.define(MyElement.is, MyElement);

// create an instance with createElement:
var el1 = document.createElement('my-element');

// ... or with the constructor:
var el2 = new MyElement();
Legacy elements
// register an element  
MyElement = Polymer({  
is: 'my-element',  
// See below for lifecycle callbacks  
created: function() { this.textContent = 'My element!'; }  
});  
// create an instance with createElement:  
var el1 = document.createElement('my-element'); 
// ... or with the constructor: 
var el2 = new MyElement();

Legacy元素的生命周期有着不同的名字:

Legacy lifecycle cb Class-based lifecycle cb
Created constructor
Ready ready
Attached connectedCallback
Detached disconnectedCallback
attributeChanged attributedChangedCallback
Hybird elements

这种方式主要是为了兼容Polymer 1.x。可以使用Class-based方式改写。详见Gesture Events。

自定义属性(properties)

自定义属性主要在properties getter中定义。可以直接传一个字符串。也可以传给他们一个Object。 Object需要包含下面几个属性:

type 数据类型

Type: constructor  Attribute type, used for deserializing from an attribute. Polymer supports deserializing the following types: Boolean, Date, Number, String, Array and Object. You can add support for other types by overriding the element's  _deserializeValue method. Unlike 0.5, the property's type is explicit, specified using the type's constructor. Seeattribute deserialization for more information.

When reflecting a property to an attribute or binding a property to an attribute, the property value is serialized to the attribute. By default, values are serialized according to value's current type, regardless of the property's type value:

String No serialization required.
Date or Number Serialized using toString. Boolean Results in a non-valued attribute to be either set (true) or removed (false). Array or Object Serialized using  JSON.stringify.

ArrayObject需要写成JSON的形式,Date需要写成任何符合Date解析形式的String。

可以重写属性序列化函数: _serializeValue method.

_serializeValue(value) { 
  if (value instanceof MyCustomType) { 
    return value.toString(); 
  }
  return super._serializeValue(value);
} 
value 默认值

Type: boolean, number, string or function. Default value for the property. If value is a function, the function is invoked and the return value is used as the default value of the property. If the default value should be an array or object unique to the instance, create the array or object inside a function. See Configuring default property values for more information

跟Vue一样,如果一个属性的默认值是以Array或者Object,那么所有该元素的实例的默认值都共享一个变量。如果要使每个元素拥有一份完全独立的拷贝的话,需要在这个值外面包一个函数。

class XCustom extends Polymer.Element { 
static get properties() { 
    return { 
      mode: { 
        type: String, 
        value: 'auto' 
      }, 
      data: { 
        type: Object, 
        notify: true, 
        value: function() { return {}; } 
      } 
    } 
}
reflectToAttribute

Type: boolean Set to true to cause the corresponding attribute to be set on the host node when the property value changes. If the property value is Boolean, the attribute is created as a standard HTML boolean attribute (set if true, not set if false). For other property types, the attribute value is a string representation of the property value. Equivalent to reflect in Polymer 0.5. See Reflecting properties to attributes for more information

值的变化是否同步更新DOM上面的attr

For a Boolean property to be configurable from markup, it must default to false. If it defaults to true, you cannot set it to false from markup, since the presence of the attribute, with or without a value, equates to true. This is the standard behavior for attributes in the web platform. If this behavior doesn't fit your use case, you can use a string-valued or number-valued attribute instead.

Boolean类型的属性只能把默认值设为false,因为标准的HTML属性行为(存在为true,不存在为false),如果必须把默认值设为true,可以用String或者Number类型属性代替。

readOnly

Type: boolean If true, the property can't be set directly by assignment or data binding.

notify

Type: boolean If true, the property is available for two-way data binding. In addition, an event, property-name-changed is fired whenever the property changes

DOM上面的属性变化是否调用回调(反向绑定)属性this.firstName的变化会触发first-name-changed事件。这些事件被用在了双向绑定系统,在外部代码里面我们可以直接使用addEventListener有点像Java里面的约定大于配置的思想,这样能使代码变得简单易懂

computed

Type: string The value is interpreted as a method name and argument list. The method is invoked to calculate the value whenever any of the argument values changes. Computed properties are always read-only. See Computed properties for more information

传入一个包含方法名和参数列表的字符串,参数必须readOnly,将该方法调用参数运行的结果作为该项的值

observer

Type: string The value is interpreted as a method name to be invoked when the property value changes. Note that unlike in 0.5, property change handlers must be registered explicitly. The propertyNameChanged method will not be invoked automatically. See Property change callbacks (observers) for more information

传入一个方法名称,当值发生变化时自动执行该方法

其他

  1. 隐式声明属性: if you add it to a data binding or add it as a dependency of an observer, computed property, or computed binding.
  2. Priavte和Protected属性:分别用__prop和_prop表示。

网易云音乐新API简述

新API采用了略微修改过的AES和RSA加密,主要用在登陆接口上,对新API进行简单的分析。

Url

估计会抓包的人都知道,Url中的api便成了weapi。比如手机登录: 原来是:http://music.163.com/api/login/cellphone/ 现在是:http://music.163.com/weapi/login/cellphone/

加密算法

核心过程如下:

 aesRsaEncrypt = function (text, pubKey, modulus, nonce) {
  const secKey = createSecretKey(16);  // 随机生成16位加密密钥
  return {
    params:  aesEncrypt(aesEncrypt(text, nonce), secKey),
    encSecKey: rsaEncrypt(secKey, pubKey, modulus)
  }
}

JS DOM API分析

Element.classList

返回DOMTokenList,IE version>=10不完全支持。 1. 不支持classList.contains的第二个参数(force) 2. add和remove方法不支持多参数 3. SVG,MathML结点没有classList属性