Web Components でどうなんだろう

最近、「Web制作者のためのCSS設計の教科書 を眺めました。Custom Elements の例を見ながら、以下のようなサンプルを書いてみました。

  • コンポーネントclass を作成する。
  • attachShadow で、シャドーDOMを使える?ようにする。
  • customElement.defineコンポーネントを登録する。名前には - が入っている必要がある。
  • 既存の要素を拡張する場合は、is 属性で登録したコンポーネントを使う。

あたりを押さえれば良いのかなぁと思いました。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <h1>Card</h1>
  <card-element data-head="タイトル">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</card-element>

  <script type="application/javascript">
    class Card extends HTMLDivElement {
      constructor() {
        super();

        this.attachShadow({mode: 'open'});

        const card = document.createElement('div');
        card.setAttribute('class', 'card');
        const cardHead = document.createElement('div');
        cardHead.setAttribute('class', 'card-head');
        cardHead.textContent = this.getAttribute('data-head')
        card.appendChild(cardHead);
        const cardBody = document.createElement('div');
        cardBody.setAttribute('class', 'card-body');
        card.appendChild(cardBody);
        cardBody.textContent = this.textContent;
        const style = document.createElement('style');
        style.textContent = `
          .card {
            background-color: #ffffff;
            border-radius: 0.4rem;
            border: 0.1rem solid #000000;
            box-shadow: 0 0.1rem 0.2rem rgba(0, 0, 0, 0.2)
          }
          .card-head {
            background-color: #f5f5f5;
            border-bottom: 0.1rem solid #c2c2c2;
            font-style: bolder;
            font-size: 1.2rem;
            letter-spacing: 0.1rem;
            padding: 0 0.4rem;
            text-align: center;
          }
          .card-body {
            padding: 1rem;
          }
        `;
        this.shadowRoot.appendChild(card);
        this.shadowRoot.appendChild(style);
      }
    }
    customElements.define('card-element', Card);
  </script>
</body>
</html>

React.js とかを使って、同じようにコンポーネントを作って、ページを構成していくけど、Safari がサポートしていれば、 autonomous components を使えば、Web Components の方が良い気がしている。