Olian04 / github-readme

A custom element that renders the readme of a github repository
https://olian04.github.io/github-readme/
MIT License
17 stars 3 forks source link

Rewrite module as an html import #10

Closed Olian04 closed 5 years ago

Olian04 commented 5 years ago

I think that writing the element as an html file could help remove a bunch of boilerplate javascript. As well as help with readability of the codebase.

Reference example of html import:

Source

Custom element:

<template id="x-ticking-paragraph">
  <style>
    p {
      color: #42b983;
    }
  </style>
  <p id="renderTarget">
  </p>
</template>

<script>
  const currentScript = document.currentScript;

  customElements.define('x-ticking-paragraph', class extends HTMLElement {
    static get observedAttributes() { return ['contents'] }

    constructor() {
      super();
      let shadowRoot = this.attachShadow({mode: 'open'});
      const template = currentScript.ownerDocument.querySelector('#x-ticking-paragraph');
      const instance = template.content.cloneNode(true);
      shadowRoot.appendChild(instance);

      this.contents = '';

      setInterval(() => {
        this.dispatchEvent(new Event('tick'));
      }, 500);
    }

    set contents(value) {
      this._contents = value;
      this.shadowRoot.getElementById('renderTarget').innerText = this._contents;
    }

    get contents() {
      return this._contents;
    }

    attributeChangedCallback(name, oldValue, newValue) {
      this[name] = newValue;
    }
  });
</script>

Usage:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>HTML import Custom element</title>
    <!-- Web Components Polyfill -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.13/webcomponents-lite.js"></script>
    <!-- Loading our component -->
    <link rel="import" href="./ticking-paragraph.html">
  </head>
  <body>
     <x-ticking-paragraph></x-ticking-paragraph>
  </body>
</html>
Olian04 commented 5 years ago

WIP: https://repl.it/repls/MintcreamOpenPasswords